PYTHON-LIST - J - Dictionary

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

PYTHON-LIST –J

172.Python - Dictionary

173.Creating Python Dictionary

 using the dict() constructor method.

174.Accessing Elements from Dictionary

 square brackets [] or with the get() method.

175.Changing and Adding Dictionary elements

176.Removing elements from Dictionary

 using the pop() method.

 using the popitem() method


 All the items can be removed at once, using the clear()
method.
 use the del keyword to remove individual items or the entire
dictionary itself.

177.Dictionary Membership Test

178.Iterating Through a Dictionary

179.Python Dictionary Methods

180.Multi-dimensional Dictionary

1|P a ge
Python - Dictionary
The dictionary is an unordered collection that contains key:value pairs separated by commas
inside curly brackets. Dictionaries are optimized to retrieve values when the key is known.

The following declares a dictionary object.

Example: Dictionary

capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}

Above, capitals is a dictionary object which contains key-value pairs inside { }. The left side of : is
a key, and the right side is a value. The key should be unique and an immutable object. A
number, string or tuple can be used as key. Hence, the following dictionaries are also valid:

Example: Dictionary Objects

d = {} # empty dictionary

numNames={1:"One", 2: "Two", 3:"Three"} # int key, string value

decNames={1.5:"One and Half", 2.5: "Two and Half", 3.5:"Three and Half"} # float key, string
value

items={("Parker","Reynolds","Camlin"):"pen", ("LG","Whirlpool","Samsung"): "Refrigerator"} #


tuple key, string value

romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5} # string key, int value

However, a dictionary with a list as a key is not valid, as the list is mutable:

Error: List as Dict Key

dict_obj = {["Mango","Banana"]:"Fruit", ["Blue", "Red"]:"Color"}

But, a list can be used as a value.

Example: List as Dictionary Value

dict_obj = {"Fruit":["Mango","Banana"], "Color":["Blue", "Red"]}

2|P a ge
The same key cannot appear more than once in a collection. If the key appears more than once,
only the last will be retained. The value can be of any data type. One value can be assigned to
more than one key.

Example: Unique Keys

>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}


>>> numNames
{1:"One", 2:"Two", 3:"Three"}

The dict is the class of all dictionaries, as shown below.

Example: Distinct Type

>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}


>>> type(numNames)
<class 'dict'>

Creating Python Dictionary


Creating a dictionary is as simple as placing items inside curly braces {} separated by commas.

An item has a key and a corresponding value that is expressed as a pair (key: value).

While the values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.

# empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair


my_dict = dict([(1,'apple'), (2,'ball')])

As you can see from above, we can also create a dictionary using the built-in dict() function.

3|P a ge
Using the dict() constructor method.
A dictionary can also be created using the dict() constructor method.

Example: dict() Constructor Method


>>> emptydict = dict()
>>> emptydict
{}
>>> numdict = dict(I='one', II='two', III='three')
>>> numdict
{'I': 'one', 'II': 'two', 'III': 'three'}

Accessing Elements from Dictionary


While indexing is used with other data types to access values, a dictionary uses keys. Keys can be
used either inside square brackets [] or with the get() method.

If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary. On
the other hand, the get() method returns None if the key is not found.

# get vs [] for retrieving elements


my_dict = {'name': 'Jack', 'age': 26}

# Output: Jack
print(my_dict['name'])

# Output: 26
print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error


# Output None
print(my_dict.get('address'))

# KeyError
print(my_dict['address'])

Output

Jack
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>

4|P a ge
print(my_dict['address'])
KeyError: 'address'

Changing and Adding Dictionary elements


Dictionaries are mutable. We can add new items or change the value of existing items using an
assignment operator.

If the key is already present, then the existing value gets updated. In case the key is not present,
a new (key: value) pair is added to the dictionary.

# Changing and adding Dictionary Elements


my_dict = {'name': 'Jack', 'age': 26}

# update value
my_dict['age'] = 27

#Output: {'age': 27, 'name': 'Jack'}


print(my_dict)

# add item
my_dict['address'] = 'Downtown'

# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}


print(my_dict)

Output

{'name': 'Jack', 'age': 27}


{'name': 'Jack', 'age': 27, 'address': 'Downtown'}

Removing elements from Dictionary


We can remove a particular item in a dictionary by using the pop() method. This method
removes an item with the provided key and returns the value.

The popitem() method can be used to remove and return an arbitrary (key, value) item pair from
the dictionary. All the items can be removed at once, using the clear() method.

We can also use the del keyword to remove individual items or the entire dictionary itself.

# Removing elements from a dictionary

# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# remove a particular item, returns its value

5|P a ge
# Output: 16
print(squares.pop(4))

# Output: {1: 1, 2: 4, 3: 9, 5: 25}


print(squares)

# remove an arbitrary item, return (key,value)


# Output: (5, 25)
print(squares.popitem())

# Output: {1: 1, 2: 4, 3: 9}
print(squares)

# remove all items


squares.clear()

# Output: {}
print(squares)

# delete the dictionary itself


del squares

Dictionary Membership Test


We can test if a key is in a dictionary or not using the keyword in. Notice that the membership
test is only for the keys and not for the values.

# Membership Test for Dictionary Keys


squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

# Output: True
print(1 in squares)

# Output: True
print(2 not in squares)

# membership tests for key only not value


# Output: False
print(49 in squares)

Output

True
True
False

Iterating Through a Dictionary


We can iterate through each key in a dictionary using a for loop.

6|P a ge
# Iterating through a Dictionary
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])

Output

1
9
25
49
81

Python Dictionary Methods


Methods that are available with a dictionary are tabulated below. Some of them have already
been used in the above examples.

Method Description
clear() Removes all items from the dictionary.
copy() Returns a shallow copy of the dictionary.

fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to None).

get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).
items() Return a new object of the dictionary's items in (key, value) format.
keys() Returns a new object of the dictionary's keys.
Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key
pop(key[,d])
is not found, it raises KeyError.

popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty.

Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and
setdefault(key[,d])
returns d (defaults to None).
update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing keys.
values() Returns a new object of the dictionary's values

7|P a ge
Dictionary Built-in Functions
Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to
perform different tasks.

Function Description

all() Return True if all keys of the dictionary are True (or if the dictionary is empty).

any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.

len() Return the length (the number of items) in the dictionary.

cmp() Compares items of two dictionaries. (Not available in Python 3)

sorted() Return a new sorted list of keys in the dictionary.

Access Dictionary using For Loop


Use the for loop to iterate a dictionary in the Python script.

Example: Access Dictionary Using For Loop


capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}

for key in capitals:


print("Key = " + key + ", Value = " + capitals[key])
Output
Key = 'USA', Value = 'Washington D.C.'
Key = 'France', Value = 'Paris'
Key = 'India', Value = 'New Delhi'

Retrieve Dictionary Keys and Values


The keys() and values() methods return a view objects containing keys and values respectively.

Example: keys()
>>> d1 = {'name': 'Steve', 'age': 21, 'marks': 60, 'course': 'Computer Engg'}
>>> d1.keys()
dict_keys(['name', 'age', 'marks', 'course'])
>>> d1.values()
dict_values(['Steve', 21, 60, 'Computer Engg'])

8|P a ge
Check Dictionary Keys
You can check whether a paritular key exists in a dictionary collection or not usng the in or not
in keywords, as shown below. Note that it only checks for keys not values.

Example: Check Keys


>>> captains = {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'}
>>> 'England' in captains
True
>>> 'India' in captains
True
>>> 'France' in captains
False
>>> 'USA' not in captains
True

Multi-dimensional Dictionary
Let's assume there are three dictionary objects, as below:

Example: Dictionary
>>> d1={"name":"Steve","age":25, "marks":60}
>>> d2={"name":"Anil","age":23, "marks":75}
>>> d3={"name":"Asha", "age":20, "marks":70}

Let us assign roll numbers to these students and create a multi-dimensional dictionary with roll
number as key and the above dictionaries at their value.

Example: Multi-dimensional Dictionary


>>> students={1:d1, 2:d2, 3:d3}
>>> students
{1: {'name': 'Steve', 'age': 25, 'marks': 60}, 2: {'name': 'Anil', 'age': 23, 'marks': 75}, 3: {'name':
'Asha', 'age': 20, 'marks': 70}}<

The student object is a two-dimensional dictionary. Here d1, d2, and d3 are assigned as values to
keys 1, 2, and 3, respectively. The students[1] returns d1.

Example: Access Multi-dimensional Dictionary


>>> students[1]
{'name': 'Steve', 'age': 25, 'marks': 60}
>>> students[1]['age']
25

9|P a ge
Accessing an element of a nested dictionary
In order to access the value of any key in the nested dictionary, use indexing [] syntax.

# Creating a Dictionary

Dict = {'Dict1': {1: 'Geeks'},

'Dict2': {'Name': 'For'}}

# Accessing element using key

print(Dict['Dict1'])

print(Dict['Dict1'][1])

print(Dict['Dict2']['Name'])

Output:

{1: 'Geeks'}
Geeks
For

U:Python-Dictionary Program-(1-15)

10 | P a g e

You might also like