UrbanPro
true

Learn Python Training from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

Python Dictionary

Mohommed Iqbal Hawre
15/05/2017 0 0

Python dictionary is an unordered collection of items. While other compound datatypes have only value as an element, a dictionary has a key: value pair. Dictionaries are optimized to retrieve values when the key is known.

Python Dictionary Creating

Creating a dictionary is as simple as placing items inside curly braces { } separated by comma. An item has a key and the corresponding value expressed as a pair, key: value. While values can be of any datatype and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique. We can also create a dictionary using the built-in function dict().

# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'Monday', 2: 'Tuesday'}
# dictionary with mixed keys
my_dict = {'name': 'matmock', 1: [12, 4, 33]}
# using dict()
my_dict = dict({1:'Monday', 2:'Tuesday'})
# from sequence having each item as a pair
my_dict = dict([(1,'Monday'), (2,'Tuesday')])

Python Dictionary Accessing Elements

While indexing is used with other container types to access values, dictionary uses keys. Key can be used either inside square brackets or with the get() method. The differencewhile using get() is that it returns None instead of KeyError, if the key is not found.

>>> my_dict = {'name':'matmock', 'age': 2}
>>> my_dict['name']
'matmock'
>>> my_dict.get('age')
2
>>> my_dict.get('address')
>>> my_dict['address']
...
KeyError: 'address'

Python Dictionary Comprehension

Dictionary comprehension is an elegant and concise way to create new dictionary from an iterable in Python. Dictionary comprehension consists of an expression pair (key: value) followed by for statement inside curly braces {}. Here is an example to make a dictionary with each item being a pair of a number and its square.

>>> squares = {x: x*x for x in range(6)}
>>> squares
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

This code is equivalent to

squares = {}
for x in range(6):
squares[x] = x*x

A dictionary comprehension can optionally contain more for or if statements. An optional if statement can filter out items to form the new dictionary. Here are some examples to make dictionary with only odd items.


>>> odd_squares = {x: x*x for x in range(11) if x%2 == 1}
>>> odd_squares
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

Python Dictionary Append

Dictionary are mutable. We can add new items or change the value of existing items using assignment operator. If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.

>>> my_dict
{'age': 2, 'name': 'matmock'}
>>> my_dict['age'] = 2.5 # update value
>>> my_dict
{'age': 2.5, 'name': 'matmock'}
>>> my_dict['address'] = 'matmock.in' # add item
>>> my_dict
{'address': 'matmock.in', 'age': 2.5, 'name': 'matmock'}

Python Dictionary Remove or Delete Element

We can remove a particular item in a dictionary by using the method pop(). This method removes as item with the provided key and returns the value. The method, popitem() can be used to remove and return an arbitrary item (key, value) form 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.


>>> squares = {1:1, 2:4, 3:9, 4:16, 5:25} # create a dictionary
>>> squares.pop(4) # remove a particular item
16
>>> squares
{1: 1, 2: 4, 3: 9, 5: 25}
>>> squares.popitem() # remove an arbitrary item
(1, 1)
>>> squares
{2: 4, 3: 9, 5: 25}
>>> del squares[5] # delete a particular item
>>> squares
{2: 4, 3: 9}
>>> squares.clear() # remove all items
>>> squares
{}
>>> del squares # delete the dictionary itself
>>> squares
...
NameError: name 'squares' is not defined

 

Python Dictionary Functions

Python includes following dictionary functions

Sr.No Python Dictionary Function with Description
1 cmp(dict1, dict2)
Compares elements of both dict.
2 len(dict)
Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
3 str(dict)
Produces a printable string representation of a dictionary
4 type(variable)
Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.

 

Python Dictionary Methods


Python includes following dictionary methods

Sr.No Python Dictionary Methods with Description
1 dict.clear()
Removes all elements of dictionary dict

 

2 dict.copy()

Returns a shallow copy of dictionary dict

3 dict.fromkeys()

Create a new dictionary with keys from seq and values set to value.

4 dict.get(key, default=None)

For key key, returns value or default if key not in dictionary

5

dict.has_key(key)

Returns true if key in dictionary dict, false otherwise

6 dict.items()

Returns a list of dict's (key, value) tuple pairs

7 dict.keys()

Returns list of dictionary dict's keys

8 dict.setdefault(key, default=None)

Similar to get(), but will set dict[key]=default if key is not already in dict

9 dict.update(dict2)

Adds dictionary dict2's key-values pairs to dict

10 dict.values()

Returns list of dictionary dict's values

0 Dislike
Follow 0

Please Enter a comment

Submit

Other Lessons for You

Python - Solving Ordinary Differential Equations - Predator Prey Model aka Lotka Volterra Equations
This is an assignment in Python, I contributed to a numerical Python MOOC from George Washington University. The link to this assignment on github is here. The Lotka–Volterra equations, also...
S

Sri Vallabha Deevi

0 0
1

Visualize your python code
Hi All, Many developers in the beginning of their career want to visualize how their code is working and the program flow. You can use the following link to visualize your python code. http://www.pythontutor.com/visualize.html#mode=edit ...

Identity operators
Identity operators Operation Syntax Function Identity a is b is_(a, b) Membership operators Operation Syntax Function Containment obj in seq contains(seq, obj)

Python programming - Applications
If you’re thinking of learning Python? Or if you recently started learning it? You may be asking yourself: "What exactly can I use Python for?" There are so many applications for python, but there...

Python Demo
https://www.youtube.com/watch?v=8AEhpZ4lbOI
X

Looking for Python Training Classes?

The best tutors for Python Training Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Learn Python Training with the Best Tutors

The best Tutors for Python Training Classes are on UrbanPro

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more