Dictionary

A place where you can post Python-related tutorials you made yourself, or links to tutorials made by others.

Dictionary

Postby metulburr » Tue Feb 12, 2013 2:35 pm

You can think of Dictionaries as a collection of data that is unorganized, unlike lists. Items in dictionaries are stored and fetched by a key, instead of a positional offset. Dictionaries can grow and shrink and can contain any objects at any nested level. They can also be changed in place. However, dictionaries do not support the sequence operations that work on strings and lists, such as slicing and concatenation, etc. They map keys to values. Dictionaries are written as {key:value} pairs, separated by commas.
Code: Select all
>>> dicter = {'fruit':'apple', 'veggie':'celery'}
>>> dicter
{'fruit': 'apple', 'veggie': 'celery'}
>>> dicter['fruit']
'apple'
>>> dicter['veggie']
'celery'

Here we create a dictionary. The 'fruit' and 'veggie' are the keys and the 'apple' and 'celery' are the values. We use the square bracket to index dictionaries by key as we did to index lists by offsets. The left to right positional order does not matter as it will change due to its unordered collection. The first key:value pair, for example, may not always be the same.
Code: Select all
>>> d1 = {'name':'micah', 'age':25}
>>> d1
{'age': 25, 'name': 'micah'}
>>> d2 = {}
>>> d2['name'] = 'micah'
>>> d2['age'] = 25
>>> d2
{'age': 25, 'name': 'micah'}
>>> d3 = dict(name='micah', age=25)
>>> d3
{'age': 25, 'name': 'micah'}
>>> dict([('name', 'micah'),('age', 25)])
{'age': 25, 'name': 'micah'}

Here is an example of other ways to create dictionaries. All 4 make the same dictionary. The first is good if you can spell out the whole dictionary ahead of time. The second is good if you need to make one field at a time on teh fly. The third however requires all keys to be strings. The fourth is good if you need to build up keys and values as sequences at runtime.

In place change
Code: Select all
>>> dicter['bread'] = 'wheat'
>>> dicter
{'fruit': 'apple', 'Vegie': 'celery', 'bread': 'wheat'}

This is the form of adding a new dictionary entry.
Code: Select all
>>> d = {'one':1, 'two':2}
>>> d['two']
2
>>> d['nested'] = {'abc':123}
>>> d
{'nested': {'abc': 123}, 'two': 2, 'one': 1}
>>> d['nested']
{'abc': 123}
>>> d['nested']['abc']
123

This example shows adding a new entry, however it is a nested dictionary. The last statement shows how to get a nested dictionary value. It is the same as lists, except using keys.

Dictionary Methods
Dicitonary methods are like any other methods. They are built-ins that affect only dictionaries.

dict.keys(), dict.values(), dict.items()
Code: Select all
>>> d = {'one':1, 'two':2}
>>> d
{'two': 2, 'one': 1}
>>> list(d.keys())
['two', 'one']
>>> list(d.values())
[2, 1]
>>> list(d.items())
[('two', 2), ('one', 1)]

The method keys() returns all keys in the dictionary. The method values() returns all the values. The method items() returns a tuple of the (key,value) pair. These methods make it very easy to loop through all keys and find a specific key, for example, and get the value of that key.
Code: Select all
>>> d['test'] = {'three':3}
>>> d
{'test': {'three': 3}, 'two': 2, 'one': 1}
>>> list(d.keys())
['test', 'two', 'one']
>>> list(d.values())
[{'three': 3}, 2, 1]
>>> list(d.items())
[('test', {'three': 3}), ('two', 2), ('one', 1)]

Here we add a nested dictionary and use the same methods as we did before. You will notice that the keys() do no show the nested keys. You will need to use a loop to go into the nested dictionary to get the ame results with the nested one. However the values() method will have a value as the nested dictionary. The items() will show tuple form.

dict.get()
Trying to call a dicitonary key that does not exist will raise a KeyError. You can either use a try/except to catch the error or you can use the get() method. The get method will 'get' the value of the key and if it does not exist, will return the value None.
Code: Select all
>>> d
{'test': {'three': 3}, 'two': 2, 'one': 1}
>>> print(d.get('test'))
{'three': 3}
>>> print(d.get('tester'))
None
>>> d['tester']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'tester'
>>> print(d.get('tester', 101))
101

By default, the get() method will return None. You can change the value that it returns with a second argument if no key is found. The 101 has returned due to the key d['tester'] not existing.

dict.update()
The update() method can be used to add new key:value pairs to the dictionary. If the key already exists, the value will be 'updated' to the new value.
Code: Select all
>>> dicter = {'one':1, 'two':2}
>>> dicter
{'two': 2, 'one': 1}
>>> dicter2 = {'three':3}
>>> dicter.update(dicter2)
>>> dicter
{'three': 3, 'two': 2, 'one': 1}
>>> dicter.update({'one':100})
>>> dicter
{'three': 3, 'two': 2, 'one': 100}


dict.pop()
The pop() method will do the same as it did with lists, except it takes a key instead of a position. It will delete the key and return the value it had.
Code: Select all
>>> d = {'one':1, 'two':2}
>>> d
{'two': 2, 'one': 1}
>>> d.pop('two')
2
>>> d
{'one': 1}


dict.fromkeys()
Provided you want all the same values for each key, you can use the fromkeys() method to create a dictionary with keys all the same. Hover a for loop would do the same and be more productive and adaptable.
Code: Select all
>>> d.fromkeys(['a','b','c','d'],0)
{'a': 0, 'c': 0, 'b': 0, 'd': 0}
>>> d.fromkeys(['a','b','c','d'])
{'a': None, 'c': None, 'b': None, 'd': None}
>>> d.fromkeys(['a','b','c','d'],'tester')
{'a': 'tester', 'c': 'tester', 'b': 'tester', 'd': 'tester'}


dict.clear()
The method clear() will completely wipe out the dictionary.
Code: Select all
>>> d = {'test':1, 'tester':2}
>>> d
{'test': 1, 'tester': 2}
>>> d.clear()
>>> d
{}


sorting a dictionary
Code: Select all
test = {'e':1, 'a':2, 'f':4, 'b':5, 'd':7, 'c':6, 'g':3}

you can return a list of the dictionary keys sorted using the built-in function sorted()
Code: Select all
print(sorted(test.keys()))
print(sorted(test))


you can return a list of the dictionary values sorted:
Code: Select all
print(sorted(test.values()))


you can return a list of the dictionary key's sorted by its value:
Code: Select all
sorted_values = sorted(test.items(), key=lambda x: x[1])
print(sorted_values)


you can return a list of the dictionary sorted by its keys:
Code: Select all
sorted_keys = sorted(test.items(), key=lambda x: x[0])
print(sorted_keys)
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1564
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Return to Tutorials

Who is online

Users browsing this forum: No registered users and 1 guest