Working with Dictionaries in python

Dictionaries in Python are a sequence of key-value pairs, with each key having an associated value. In other languages, dictionaries are known as associative memories or associative arrays.

Basically, a dictionary in Python is an unordered sequence of key-value pairs, enclosed in curly braces. The items in a dictionary (key-value pairs) are separated by commas. Each key is associated with a value by a colon (:), and to access a value, you have to use the key.


D = {'key':'value'}

Dictionaries are heterogenous, meaning that a dictionary can contain items of different types like numbers, strings, lists, tuples and even dictionaries.


fruits = {1:'apple', 2:'grape', 3:'mange', 4:'orange'}

D = {'name':'Andrew', 'age':23, 'married':False, 'colors':['red', 'green'], 'contact':{'phone': '0907 938 403'}}

Creating an empty dictionary

You can create an empty dictionary with the dict() function or with an empty curly brace {} as shown below:


D1 = dict()

D2 = {}

print(D1)

print(D2)


#outputs

#{}

#{}

Accessing items in a dictionary

Dictionaries are an unordered sequence of items of key-value pairs, and you access the items or values in a dictionary through the keys.  Unlike lists and tuples, items in a dictionary are accessed by their keys and not indexes.

To access values in a dictionary, you have to put the key inside a square bracket after the name of the dictionary.


D = {'name':'Andrew', 'age':23, 'married':False, 'colors':['red', 'green']}

print(D['name'])

print(D['age'])

print(D['colors'])

#outputs

#Andrew

#23

#['red', 'green']

As you can see from the example above, a dictionary can contain objects of different data types. One of the items contained in the dictionary D is an item with the key – colors. It is associated with a value, which happens to be a list – [‘red’, ‘green’].

To access the items contained in a list which is nested in a dictionary, you have to use the indexes of the items of interest.


print(D['colors'][1])
#green

Adding and updating items in a dictionary

You can easily an item to a dictionary by providing the name of the dictionary, followed by the square bracket containing the key, and assigning it to a value.

If the key is not existing in the dictionary, it will insert an item with the key and value into the dictionary, otherwise, it will update an already existing key with the new value.


student = {}

student['name'] = 'Adam'

print(student)

#output
#{'name': 'Adam'}
student['name'] = 'Eve'

print(student)

#output
#{'name': 'Eve'}

Deleting an Item in a dictionary

To delete an item in a dictionary, simply use the keyword del followed by the name of the dictionary and the key enclosed in a square bracket.


student = {'name': 'Adam', 'age': 21}

del student['name']

print(student)

#output
#{'age': 21}

Built-in methods for dictionaries

These are methods that enable you to create, alter or manipulate the items in a dictionary.

Clear

The clear() method removes all the items in a dictionary as shown below.


D = {'name':'Andrew', 'age':23, 'married':False, 'colors':['red', 'green']}

D.clear()

print(D)

#outputs

#{}

Copy

This method is used to create a dictionary with a copy of another dictionary.


D1 = {'name':'Andrew', 'age':23, 'married':False, 'colors':['red', 'green']}


D2 = D1.copy()


print(D2)


#outputs

#{'name': 'Andrew', 'age': 23, 'married': False, 'colors': ['red', 'green']}

Fromkeys

This method allows you to create a new dictionary from a sequence of items as keys and optional default values for the keys.

It expects two arguments: a collection like a list or a tuple, and an optional default value (which is set to None).

The syntax is:


D = dict.fromkeys(['name', 'age', 'gender'], '-')

print(D)

D = dict.fromkeys(['name', 'age', 'gender'])

print(D)

#outputs

#{'name': '-', 'age': '-', 'gender': '-'}

#{'name': None, 'age': None, 'gender': None}

If no argument is provided for default values for the items, the items will have values of None.

Get

This is used to return the value of a given key in a dictionary if the key is available.


student = {'age': 21, 'gender': 'male'}

age = student.get('age')

gender = student.get('gender')


print(age)

print(gender)


#output

#21

#male

Items

This method returns a dictionary object of the items in a dictionary in keys and value pairs.


student = {'age': 21, 'gender': 'male'}

print(student.items())

#output

#dict_items([('age', 21), ('gender', 'male')])

Keys

This method returns a dictionary object of the keys in a given dictionary as shown below:


student = {'age': 21, 'gender': 'male'}

print(student.keys())

#output

#dict_keys(['age', 'gender'])

Pop

This is used to remove items from a dictionary. Unlike in sequences such as lists, sets or tuples, you are required to provide the key as an argument in the pop() method. It removes the item and returns the value of the item as shown below:


D =  {'name': 'Kenny', 'age': 21, 'gender': 'male'}


person = D.pop('name')

print(person)

print(D)

age = D.pop('age')

print(age)

print(D)

#output

#Kenny

#{'age': 21, 'gender': 'male'}

#21

#{'gender': 'male'}

Popitem

This behaves like the pop() method, except that it doesn’t require an argument. It removes the last item in a dictionary and returns a tuple of the key-value pair.


D =  {'name': 'Kenny', 'age': 21, 'gender': 'male'}


person = D.popitem()

print(person)

print(D)

person = D.popitem()

print(person)

print(D)


#output

#('gender', 'male')

#{'name': 'Kenny', 'age': 21}

#('age', 21)

#{'name': 'Kenny'}

Setdefault

This is used to return the value of a given key or assign a key to a value if the key is not in the dictionary.


D =  {'name': 'Kenny', 'age': 21, 'gender': 'male'}

name = D.setdefault('name')

print(name)

level = D.setdefault('level')

print(level)

print(D)

complexion = D.setdefault('complexion', 'black')

print(complexion)

print(D)

#output

#Kenny

#None

#{'name': 'Kenny', 'age': 21, 'gender': 'male', 'level': None}

#black

#{'name': 'Kenny', 'age': 21, 'gender': 'male', 'level': None, 'complexion': 'black'}

Update

This method is used to add the items of a dictionary to an already existing dictionary.


student = {'name': 'kevin', 'age': 21, 'gender': 'male', 'major': 'engineering'}

level  = {'year':2}

student.update(level)

print(student)

#output

#{'name': 'kevin', 'age': 21, 'gender': 'male', 'major': 'engineering', 'year': 2}

Values

This method returns a dictionary object of values containing a given dictionary.


student = {'age': 21, 'gender': 'male'}

print(student.values())

#output

#dict_values([21, 'male'])

Enumerate

The enumerate() function converts a dictionary into a list pairing the indexes of each item with the keys.


D = {'name':'Kenny', 'age':21, 'phone':'0903-843-9234', 'major':'engineering'}

print(enumerate(D))

print(list(enumerate(D)))


#looping and printing the items


for item in enumerate(D):

    print(item)


#output

#<enumerate object at 0x11192b780>

#[(0, 'name'), (1, 'age'), (2, 'phone'), (3, 'major')]

#(0, 'name')

#(1, 'age')

#(2, 'phone')

#(3, 'major')

Looping a dictionary

Like every other sequence, you can loop through the items in a dictionary. In the following example, we will loop through the items, keys and values of a dictionary.


D = {'name':'Kenny', 'age':21, 'phone':'0903-843-9234', 'major':'engineering'}

#looping through the keys in a dictionary

for key in D:

    print(key)

#output

#name

#age

#phone

#major


#looping through the keys in a dictionary

for key in D.keys():

    print(key)

#output

#name

#age

#phone

#major

#looping through the values in a dictionary

for value in D.values():

    print(value)


#output

#Kenny

#21

#0903-843-9234

#engineering

#looping through the items in a dictionary

for item in D.items():

    print(item)

#output

#('name', 'Kenny')

#('age', 21)

#('phone', '0903-843-9234')

#('major', 'engineering')

Comprehension in dictionaries

Dictionary comprehension starts with curly braces, instead of the square bracket as obtainable in the list comprehension.

Unlike the set comprehension that equally starts with curly braces, the key-value pair precedes the opening curly braces in the dictionary comprehension.


{num:num**2 for num in [1,2,3,4]}

{1: 1, 2: 4, 3: 9, 4: 16}

You can also use the zip function in dictionary comprehension to combine two lists into a dictionary of key-value pairs.


D = {x for x in zip([1,2,3], [4,5,6])}

print(D)

#output

#{(2, 5), (1, 4), (3, 6)}

 

Leave a Reply

Your email address will not be published. Required fields are marked *