Python - (Dictionary|Map)

Card Puncher Data Processing


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.


Dictionaries are enclosed in curly braces that contains key:

dict_name = {'key1' : 1, 'key2' : 2, 'key3' : 3}


  • dict_name is the dictionary
  • of three key-value pairs
    • 'key1' : 1
    • 'key2' : 2
    • 'key3' : 3

An empty dictionary:

dict_name = {}


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}


new_dic = {}
new_dic[1] = {}
new_dic[1][2] = 5


prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3,


Access the value of a key

ie Indexing.

print d['key1']

>>> {'key1' : 1, 'key2' : 2, 'key3' : 3}['key1']

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)

print myDict.items() # 


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.


Check if a key exist

if key in d:
        d[key] += 1
        d[key] = 1

In a comprehension:

>>> myDict = {'Nico':40}
>>> 'Gerard' in myDict
>>> myDict['Gerard'] if 'Gerard' in myDict else 'Not Present'
'Not Present'


Python - (Loop|Iteration)


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:

map = {1:1,2:2}
for k, v in iter(map.items()):
  • 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


Python - Comprehension (Iteration)

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']

Documentation / Reference

Discover More
Card Puncher Data Processing
Ansible - Dict (Map)

value type of a variable The map variable in ansible is based on the python dict. See example:
Imperative Vs Functional
Functional Programming - Map

A page the map functional programming function The map method creates a new collection with the results of calling a provided function on every element in the collection. The map operation produces...
Image Vector
Linear Algebra - Vector

tuple in Linear algebra are called vector. A vector is a list of scalar (real number) used to represent a When the letters are in bold in a formula, it signifies that they're vectors, To represent...
Card Puncher Data Processing
Object Type - Class

The type of an object is its class. See
Card Puncher Data Processing
Python - Class

in Python The difference with a standard class implementation is that in Python, Classes are objects because the class keyword will creates an object. Only a class object is capable of creating objects. A...
Card Puncher Data Processing
Python - Collection

collection in Python: Data Type: Type Sequence (Ordered) Mutable Duplicate Yes Yes Yes Yes No Yes No Yes No No Yes No
Card Puncher Data Processing
Python - Comprehension (Iteration)

Comprehension are a way to loop over elements of: a , , , tuple, , or . Comprehensions permit to build collections out of other collections. Comprehensions allow one to express computations...
Card Puncher Data Processing
Python - Data Type

data (type|structure) in Python of a name generally a variable objecttypeintsstringsfunctionsclassesclass - an integer is a positive or negative whole number. float booleans (True...
Card Puncher Data Processing
Python - Json

Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object. For json.load, you should pass a file like object with a read function defined. Serialize...
Card Puncher Data Processing
Python - List

Lists are used to store a collection of different pieces of information in a sequence order of under a single variable name. A list can be used to implement a . A list is mutable whereas a tuple is not....

Share this page:
Follow us:
Task Runner