Python Dictionary Tutorial

Python dictionary is the only built-in mapping data structure where you can refer to each element by a name basically a key value that can be either a number, a string, or even a tuple unlike lists where the index is always an integer. With the help of dictionary you can keep meaningful data much like a database where you have a key and then associated information. For example if you have an employee database or say dictionary in Python then they key can be an employee Id or a name and then the associated values can be age, salary, department, etc.

Example:
employees = {'John':{'age':24,'salary':'10000'},'Ed':{'age':53,'salary':'51000'}}
Dictionaries consist of keys and their corresponding values. In the example above, the names are the keys and values are also dictionary that keep the age and the salary for the given employee. Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces.

How to create an empty dictionary

>>> employees = {}
>>> employees
{}
>>> employee = dict()
>>> employee
{}

How to intialize a dictionary

>>> employee1 = {'salary': '51000', 'age': 53}
>>> employee2 = {'salary': '10000', 'age': 24}
>>> employees = {'Ed':employee1,'John':employee2}
>>> employees
{'Ed': {'salary': '51000', 'age': 53}, 'John': {'salary': '10000', 'age': 24}}

How to create a dictionary from name and value pairs

The dict() constructor returns a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.
>>> employee = dict(name='John',salary=10000,age=24)
>>> employee
{'salary': 10000, 'age': 24, 'name': 'John'}
>>> employee = dict({'name':'John','salary':10000,'age':24})
>>> employee
{'salary': 10000, 'age': 24, 'name': 'John'}
>>> employee = dict(zip(('name', 'salary','age'), ('John', 10000, 24)))
>>> employee
{'salary': 10000, 'age': 24, 'name': 'John'}
>>> employee = dict([['name', 'John'], ['salary', 10000], ['age', 24]])
>>> employee
{'salary': 10000, 'age': 24, 'name': 'John'}

How to access values in a dictionary

>>> employees = {'John':{'age':24,'salary':'10000'},'Ed':{'age':53,'salary':'51000'}}
>>> employee1 = employees['John']
>>> employee2 = employees['Ed']
>>> employee1
{'salary': '10000', 'age': 24}
>>> employee2
{'salary': '51000', 'age': 53}
>>> johnSalary = employee1['salary']
>>> johnSalary
'10000'
>>> johnSalary = employees['John']['salary']
>>> johnSalary
'10000'

How to update an existing entry in the dictionary

>>> employee = {'name':'John','salary':10000,'age':24}
>>> employee['salary'] = 20000
>>> employee
{'salary': 20000, 'age': 24, 'name': 'John'}

How to insert an entry in the dictionary

>>> employee = {'name':'John','salary':10000,'age':24}
>>> employee['dept'] = 'Sales'
>>> employee
{'salary': 10000, 'dept': 'Sales', 'age': 24, 'name': 'John'}

How to delete an entry from the dictionary

>>> employee = {'name':'John','salary':10000,'age':24}
>>> del employee['age']
>>> employee
{'salary': 10000, 'name': 'John'}

How to delete the dictionary

>>> employee = {'name':'John','salary':10000,'age':24}
>>> del employee
>>> employee

Traceback (most recent call last):
  File "", line 1, in 
    employee
NameError: name 'employee' is not defined

How to clear the dictionary

>>> employee = {'name':'John','salary':10000,'age':24}
>>> employee.clear()
>>> employee
{}

How to convert a dictionary to String

>>> employee = {'name':'John','salary':10000,'age':24}
>>> myString = str(employee)
>>> myString
"{'salary': 10000, 'age': 24, 'name': 'John'}"

How to find the length of the dictionary

>>> employee = {'name':'John','salary':10000,'age':24}
>>> len(employee)
3
>>> employee['dept'] = 'Sales'
>>> len(employee)
4

How to copy a dictionary

Also known as shallow copy
>>> employees = {'John':{'age':24,'salary':'10000'},'Ed':{'age':53,'salary':'51000'}}
>>> newEmployees = employees.copy()
>>> newEmployees
{'Ed': {'salary': '51000', 'age': 53}, 'John': {'salary': '10000', 'age': 24}}
>>> newEmployees['John'] = {'age':35}
>>> newEmployees
{'Ed': {'salary': '51000', 'age': 53}, 'John': {'age': 35}}
>>> employees
{'Ed': {'salary': '51000', 'age': 53}, 'John': {'salary': '10000', 'age': 24}}
>>> newEmployees['John']['age'] = 55
>>> newEmployees
{'Ed': {'salary': '51000', 'age': 53}, 'John': {'age': 55}}
>>> employees
{'Ed': {'salary': '51000', 'age': 53}, 'John': {'salary': '10000', 'age': 24}}

Shallow copy versus Deep copy in dictionary

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances).
  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Here is an example where the shallow copy fails
>>> employees
{'Ed': {'salary': '51000', 'age': 53}, 'John': {'salary': '10000', 'age': 24}}
>>> employees = {'name':'John','cars':['Honda','BMW','Lexus']}
>>> newEmployees = employees.copy()
>>> newEmployees['cars'].remove('BMW')
>>> employees
{'cars': ['Honda', 'Lexus'], 'name': 'John'}
>>> newEmployees
{'cars': ['Honda', 'Lexus'], 'name': 'John'}
Now let's use deep copy for the same example
>>> from copy import deepcopy
>>> employees = {'name':'John','cars':['Honda','BMW','Lexus']}
>>> newEmployees = deepcopy(employees)
>>> newEmployees['cars'].remove('BMW')
>>> employees
{'cars': ['Honda', 'BMW', 'Lexus'], 'name': 'John'}
>>> newEmployees
{'cars': ['Honda', 'Lexus'], 'name': 'John'}

How to create a new dictionary with the given keys

>>> employee = dict.fromkeys(['name','salary','age'])
>>> employee
{'salary': None, 'age': None, 'name': None}
>>> employee = dict.fromkeys(['name','salary','age'],'Default')
>>> employee
{'salary': 'Default', 'age': 'Default', 'name': 'Default'}

How to read an entry from the dictionary using the get() method

The get() method is better than accessing the entries by directly using the key values. Here is why? If you try to access an entry by the key and it doesn't exists they direct access method with throw an exception whereas if you user get method then you just get a value of None that you can check against.
>>> employee = {'name':'John','salary':10000,'age':24}
>>> department = employee['dept']

Traceback (most recent call last):
  File "", line 1, in 
    department = employee['dept']
KeyError: 'dept'
>>> department = employee.get('dept')
>>> department
>>> print(department)
None
>>> name = employee.get('name')
>>> name
'John'

How to check if a given key exists in the dictionary

The has_key() method checks whether a dictionary has a given key.
>>> employee = {'name':'John','salary':10000,'age':24}
>>> employee.has_key('dept')
False
>>> employee.has_key('name')
True

How to update a dictionary from another one

The items in the new dictionary are added to the old one and overrides any items already there with the same keys.
>>> employee1 = {'name':'John','salary':10000,'age':24}
>>> employee2 = {'name':'Ed','salary':54000,'dept':'Sales'}
>>> employee1.update(employee2)
>>> employee1
{'salary': 54000, 'dept': 'Sales', 'name': 'Ed', 'age': 24}
>>> employee2
{'salary': 54000, 'dept': 'Sales', 'name': 'Ed'}

How remove/pop items from the dictionary

There are two methods pop() and popitem(). The popitem() method takes out entries in random fashion as there is no concept of index in a dictionary whereas with pop() you specify the key value.
>>> employee = {'name':'John','salary':10000,'age':24}
>>> employee.popitem()
('salary', 10000)
>>> employee
{'age': 24, 'name': 'John'}
>>> employee.popitem()
('age', 24)
>>> employee
{'name': 'John'}
>>> employee = {'name':'John','salary':10000,'age':24}
>>> employee.pop('age')
24
>>> employee
{'salary': 10000, 'name': 'John'}

How to get all the entries from the dictionary

>>> employee = {'name':'John','salary':10000,'age':24}
>>> myList = employee.items()
>>> for x in myList:
 print(x)

 
('salary', 10000)
('age', 24)
('name', 'John')

How to get all keys from the dictionary

>>> employee = {'name':'John','salary':10000,'age':24}
>>> myList = employee.keys()
>>> for x in myList:
 print(x)

 
salary
age
name

How to get all values from the dictionary

>>> employee = {'name':'John','salary':10000,'age':24}
>>> myList = employee.keys()
>>> for x in myList:
 print(employee.get(x))

 
10000
24
John
>>> myList = employee.values()
>>> for x in myList:
 print(x)

 
10000
24
John

How to use a dictionary for String formatting

>>> myTemplate = '''
<html>
<head><title>%(title)s</title></head>
<body>
<h1>%(title)s</h1>
<p>%(content)s</p>
</body>
</html>'''
>>> myData = {'title': 'Python Tutorial', 'content': 'String formatting using Dictionary'}
>>> myString = myTemplate % myData
>>> print(myString)

<html>
<head><title>Python Tutorial</title></head>
<body>
<h1>Python Tutorial</h1>
<p>String formatting using Dictionary</p>
</body>
</html>

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.