About
A dictionary is similar to a list, but you access values by looking up a key instead of an index.
A key can be any string or number.
A dictionary is suitable for representing functions with finite domains.
Dictionaries are great for pairing (a name with a phone number or with an e-mail address).
Dictionaries are:
- mutable. They can be changed.
- unordered
The keys must be immutable.
Articles Related
Syntax
Dictionaries are enclosed in curly braces that contains key:
dict_name = {'key1' : 1, 'key2' : 2, 'key3' : 3}
where:
- dict_name is the dictionary
- of three key-value pairs
- 'key1' : 1
- 'key2' : 2
- 'key3' : 3
An empty dictionary:
dict_name = {}
Initialization
One dimension
An empty dict is created
- with the accolade without content
myEmptyDict = {}
- or with the dict function
myEmptyDict = dict()
A dict with values can be initialized:
- with the dict function
myDict = dict(a=1,b=2,c=3)
- or directly with the accolades syntax:
myDict = {'a':1,'b':2,'c':3}
You can also construct a dictionary using a comprehension.
>>> { (x,y):x*y for x in [1,2] for y in [1,2] }
{(1, 2): 2, (1, 1): 1, (2, 1): 2, (2, 2): 4}
>>> { key:value for (key,value) in [(3,2),(4,0),(100,1)] }
{100: 1, 3: 2, 4: 0}
Multi-dimensional
new_dic = {}
new_dic[1] = {}
new_dic[1][2] = 5
Example
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3,
}
Get
Access the value of a key
ie Indexing.
print d['key1']
1
>>> {'key1' : 1, 'key2' : 2, 'key3' : 3}['key1']
1
Get the keys and/of values
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3,
}
>>> prices.keys()
dict_keys(['orange', 'apple', 'pear', 'banana'])
>>> prices.values()
dict_values([1.5, 2, 3, 4])
Get its length
The length len() of a dictionary is the number of key-value pairs it has.
print len(dict_name)
3
Print every pair in the dictionary
print myDict.items() #
Set
Add a new entry or set a new value
A new key-value pair in a dictionary is created by assigning a new key.
dict_name[new_key] = new_value
A new value is associated to a key value with the same syntax:
dict_name[existing_key] = new_value
Put a list inside a dictionary
You can put lists inside dictionaries.
dict_name['myListKey'] = ['Element1', 'Element2', 'Element3']
Delete an entry
Items can be removed from a dictionary with the del command:
del dict_name[key_name]
It will remove the key key_name and its associated value from the dictionary.
Operator
Check if a key exist
if key in d:
d[key] += 1
else:
d[key] = 1
In a comprehension:
>>> myDict = {'Nico':40}
>>> 'Gerard' in myDict
False
>>> myDict['Gerard'] if 'Gerard' in myDict else 'Not Present'
'Not Present'
Iteration
Key
for key in dict_name:
print dict_name[key]
key and value
When looping through dictionaries, the key and corresponding value can be retrieved at the same time using:
- Python 3 See Dictviews
map = {1:1,2:2}
for k, v in iter(map.items()):
print(k,':',v)
- Python 2 using the iteritems() method.
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.iteritems():
print k, v
gallahad the pure
robin the brave
Comprehension
Get the value in a list of dictionary
>>> dlist = [{'James':'Sean', 'director':'Terence'}, {'James':'Roger','director':'Lewis'}, {'James':'Pierce', 'director':'Roger'}]
>>> k = 'James'
>>> [ i[k] for i in dlist]
['Sean', 'Roger', 'Pierce']
Iterate over Key or values
>>> [2*x for x in {4:'a',3:'b'}.keys() ]
[6, 8]
>>> [x for x in {4:'a', 3:'b'}.values()]
['b', 'a']
Iterate over the pairs (key, value)
- On the pair
>>> prices = {"banana": 4, "apple": 2, "orange": 1.5, "pear": 3 }
>>> [myPair for myPair in prices.items()]
[('orange', 1.5), ('apple', 2), ('pear', 3), ('banana', 4)]
- On the value of the pairs with unpacking because the items are tuple:
>>> [fruit+' have a price of '+str(price) for (fruit,price) in prices.items()]
['orange have a price of 1.5', 'apple have a price of 2', 'pear have a price of 3', 'banana have a price of 4']
Test presence of a pair otherwise default value
>>> dlist = [{'Bilbo':'Ian','Frodo':'Elijah'},{'Bilbo':'Martin','Thorin':'Richard'}]
>>> k = 'Frodo'
>>> [ i[k] if k in i else 'NOT PRESENT' for i in dlist]
['Elijah', 'NOT PRESENT']