Python Forum
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. 


As of Python3.7+, python supports insertion order. Which means a dictionary will remember the order of items inserted into the dictionary and order them in the same way. You can depend on it.
>>> d = {'b':2}
>>> d
{'b': 2}
>>> d['a'] = 1
>>> d
{'b': 2, 'a': 1}
>>> d['d'] = 4
>>> d['c'] = 3
>>> d
{'b': 2, 'a': 1, 'd': 4, 'c': 3}
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. You could of course use a for loop, but this is quick and built-in already.
>>> 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
{}
setdefault
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
The setdefault() method returns the value of the item with the specified key. If the key does not exist, insert the key, with the specified value.
Notice that the dictionary key 'color' pertains the value 'black' even after setdefault() as python knows that the key exists and does not overwrite it. If you omit the line with color, then it does write to the dictionary.
car = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964,
  'color':'black'
}

x = car.setdefault("color", "White")

print(x)
print(car)
Output:
black {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'black'}
Below is a quick example of combining lists with common keys avoiding KeyErrors and overwriting the same key with different values by by appending them to a list as the value instead.
arr1 = ['sub1', 'sub1', 'sub2', 'sub1', 'sub1', 'sub2']
arr2 = [1.9   , 2.2   , 9.1   , 7.3   , 4.0   , 5.1   ]
 
d = {}
for key, value in zip(arr1, arr2):
    d.setdefault(key,[]).append(value)
         
print(d)
Output:
{'sub1': [1.9, 2.2, 7.3, 4.0], 'sub2': [9.1, 5.1]}
alternative version:
lists = [
['scext', '80.0'],
['scext', 'COLFUJDX440_DS11'],
['scext', 'Hard disk 1'],
['scext', '100.0'],
['scext', 'COLFUJDX440_DS11'],
['scext', 'Hard disk 2'],
['scext', '200.0'],
['scext', 'COLFUJDX440_DS11'],
['scext', 'Hard disk 3'],
['SCEXTVMD', '100.0'],
['SCEXTVMD', 'COLHG600P01_DS33'],
['SCEXTVMD', 'Hard disk 1'],
['SCEXTVMD', '40.0'],
['SCEXTVMD', 'COLHG600P01_DS33'],
['SCEXTVMD', 'Hard disk 2'],
['SCEXTVMD', '100.0'],
['SCEXTVMD', 'COLHG600P01_DS33'],
['SCEXTVMD', 'Hard disk 3'] 
]

d = {}
for lst in lists:
    key = lst[0]
    value = lst[1]
    d.setdefault(key, []).append(value)
    
print(d)
Output:
{'scext': ['80.0', 'COLFUJDX440_DS11', 'Hard disk 1', '100.0', 'COLFUJDX440_DS11', 'Hard disk 2', '200.0', 'COLFUJDX440_DS11', 'Hard disk 3'], 'SCEXTVMD': ['100.0', 'COLHG600P01_DS33', 'Hard disk 1', '40.0', 'COLHG600P01_DS33', 'Hard disk 2', '100.0', 'COLHG600P01_DS33', 'Hard disk 3']}
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]
Recommended Tutorials:


Messages In This Thread
Dictionaries - by metulburr - Sep-01-2016, 08:18 PM
RE: Dictionaries basic - by micseydel - Oct-03-2016, 07:18 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020