Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 [Basic] Dictionaries
#1
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. 
>>> 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. 
>>> 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
>>> dicter['bread'] = 'wheat'
>>> dicter
{'fruit': 'apple', 'Vegie': 'celery', 'bread': 'wheat'}
This is the form of adding a new dictionary entry. 
>>> 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()
>>> 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. 
>>> 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. 
>>> 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. 
>>> 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. 
>>> 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. 
>>> 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. 
>>> d = {'test':1, 'tester':2}
>>> d
{'test': 1, 'tester': 2}
>>> d.clear()
>>> d
{}
sorting a dictionary
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()
print(sorted(test.keys()))
print(sorted(test))
you can return a list of the dictionary values sorted:
print(sorted(test.values()))
you can return a list of the dictionary key's sorted by its value:
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:
sorted_keys = sorted(test.items(), key=lambda x: x[0])
print(sorted_keys)
Handling long if elif elif structures
instead of this...
something = 'something'

if something == 'this':
    the_thing = 1
elif something == 'that':
    the_thing = 2
elif something == 'there':
    the_thing = 3
else:
    the_thing = 4
You can do the following of either one of these
something = 'something'
options = {'this': 1, 'that': 2, 'there': 3}

the_thing = options.get(something, 4)
something = 'something'
options = {'this': 1, 'that': 2, 'there': 3}

if something in options:
    the_thing = options[something]
else:
    the_thing = 4
from collections import defaultdict

something = 'something'
options = defaultdict(lambda: 4, {'this': 1, 'that': 2, 'there': 3})

the_thing = options[something]
#2
Also worth noting here is OrderedDict, an importable extended dictionary class which supports ordering.
metulburr likes this post

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)