Dictionaries#

Table of Contents

Creating#

Creating with { }:

mydict = {'k':"v"}

Creating with dict():

mydict = dict('k':"v")

Creating with dict() using keyword notation:

mydict = dict(k="v")

Selecting#

Accessing elements:

mydict['k']

Accessing elements without missing key errors:

mydict.get('a', None)

Modification#

Adding & Changing#

Assignment:

mydict['x'] = "y"

Bulk appending / modification:

mydict.update({'k':"v"})

Removing#

Deleting elements:

del mydict['k']

Deleting elements without missing key errors:

mydict.pop('k', "valifmissing")

Delete the last item and return (k, v):

mydict.popitem()

Membership#

Check for key membership using .has_key():

mydict.has_key('k')

Check for key membership using in:

'somekey' in mydict

Check for value membership:

'someval' in mydict.values()

Joining through unpacking:

mydict = {**dict1, **dict2}

Iteration#

Iterating through values:

for k in mydict:

Iterating through keys and values:

for k, v in mydict.items():

Sorting#

Returns a sorted list of mydict.keys():

sorted(mydict)

Sort by value, return a list of tuples:

sorted(mydict.items(), key=lambda x: x[1])

Create a new dict sorted by value:

{ k: v for (k, v) in sorted(d.items(), key=lambda x: x[1]) }

Printing#

Unpack keys from dict:

print("%(first_name) %(last_name)" % person)

Aggregation#

Length:

len(mydict)

If any value is True:

any(mydict.values())

If any key or value is True (probably not desired):

any(mydict)

Misc#

Using tuples as keys:

mydict = { (5, 10): "a", (3,5): "b" }

Creating using dict comprehensions:

{x: x**2 for x in (2, 4, 6)}

Creating using dict() and zip():

dict(zip("a b c d e f".split(), range(0, 6)))

Create a new dict where keys are upper():

dict(map(lambda x: (x[0].upper(), x[1]), mydict.items() ))