Dictionary Data Structure
- We can use List, Tuple and Set to represent a group of individual objects as a single entity.
- If we want to represent a group of objects as key-value pairs then we should go for Dictionary.
Ex:
rollno—-name
phone number–address
ipaddress—domain name
- Duplicate keys are not allowed but values can be duplicated.
- Heterogeneous objects are allowed for both key and values.
- Insertion order is not preserved Dictionaries are mutable
- Dictionaries are dynamic
- indexing and slicing concepts are not applicable
Note:
In C++ and Java Dictionaries are known as “Map” where as in Perl and Ruby it is known as “Hash”
How to create Dictionary?
d = {} or d = dict() We are creating empty dictionary. We can add entries as follows
d[100]=”shashi”
d[200]=”nishi”
d[300]=”shishir”
print(d) #{100: ‘shashi’, 200: ‘nishi’, 300: ‘shishir’}
If we know data in advance then we can create dictionary as follows
d={100:’shashi’ ,200:’nishi’, 300:’shishir’}
d = {key:value, key:value}
How to access data from the dictionary?
We can access data by using keys.
d={100:’shashi’ ,200:’nishi’, 300:’shishir’}
print(d[100]) #shashi
print(d[300]) #shishir
If the specified key is not available then we will get KeyError
print(d[400]) # KeyError: 400
We can prevent this by checking whether key is already available or not by using has_key() function or by using in operator.
d.has_key(400) ==> returns 1 if key is available otherwise returns 0
But has_key() function is available only in Python 2 but not in Python 3. Hence compulsory we have to use in operator.
if 400 in d:
print(d[400])
How to update dictionaries?
d[key] = value
- If the key is not available then a new entry will be added to the dictionary with the specified key-value pair
- If the key is already available then old value will be replaced with new value.
Ex:
d={100:”shashi”,200:”nishi”,300:”shishir”}
print(d)
d[400]=”manisha”
print(d)
d[100]=”alok”
print(d)
Output
{100: ‘shashi’, 200: ‘nishi’, 300: ‘shishir’}
{100: ‘shashi’, 200: ‘nishi’, 300: ‘shishir’, 400: ‘manisha’}
{100: ‘alok’, 200: ‘nishi’, 300: ‘shishir’, 400: ‘manisha’}
How to delete elements from dictionary?
del d[key] It deletes entry associated with the specified key. If the key is not available then we will get KeyError.
Ex:
d={100:”shashi”,200:”nishi”,300:”shishir”}
print(d)
del d[100]
prnt(d)
del d[400]
Output
{100: ‘shashi’, 200: ‘nishi’, 300: ‘shishir’}
{200: ‘nishi’, 300: ‘shishir’}
KeyError: 400
clear() To remove all entries from the dictionary
Ex:
d={100:”shashi”,200:”nishi”,300:”shishir”}
print(d)
d.clear()
print(d)
Output
{100: ‘shashi’, 200: ‘nishi’, 300: ‘shishir’}
{}
del d To delete total dictionary.Now we cannot access d
Ex:
d={100:”shashi”,200:”nishi”,300:”shishir”}
print(d)
del d
print(d)
Output
{100: ‘shishir’, 200: ‘nishi’, 300: ‘shishir’}
NameError: name ‘d’ is not defined
Important functions of dictionary:
dict(): To create a dictionary
- d=dict() ===>It creates empty dictionary
- d=dict({100:”shashi”,200:”nishi”}) ==>It creates dictionary with specified elements
- d=dict([(100,”shashi”),(200,”shishir”),(300,”nishi”)])==>It creates dictionary with the given list of tuple elements
len()
Returns the number of items in the dictionary
clear(): To remove all elements from the dictionary
get(): To get the value associated with the key d.get(key)
If the key is available then returns the corresponding value otherwise returns None.It wont raise any error.
d.get(key,defaultvalue) If the key is available then returns the corresponding value otherwise returns default value.
Ex:
d={100:”shashi”,200:”nishi”,300:”shishir”}
print(d[100]) ==>shashi
print(d[400]) ==>KeyError:400
print(d.get(100)) ==shashi
print(d.get(400)) ==>None
print(d.get(100,”Guest”)) ==shashi
print(d.get(400,”Guest”)) ==>Guest
pop():
d.pop(key)
It removes the entry associated with the specified key and returns the corresponding value
If the specified key is not available then we will get KeyError
Ex:
d={100:”shashi”,200:”nishi”,300:”shishir”}
print(d.pop(100))
print(d)
print(d.pop(400))
Output
shashi
{200: ‘nishi’, 300: ‘shishir’}
KeyError: 400
popitem(): It removes an arbitrary item(key-value) from the dictionaty and returns it.
Ex:
d={100:”shashi”,200:”nishi”,300:”shishir”}
print(d)
print(d.popitem())
print(d)
Output
{100: ‘shashi’, 200: ‘nishi’, 300: ‘shishir’}
(300, ‘shishir’)
{100: ‘shashi’, 200: ‘nishi’}
- If the dictionary is empty then we will get KeyError d={}
- print(d.popitem()) ==>KeyError: ‘popitem(): dictionary is empty’
keys(): It returns all keys associated eith dictionary
Ex:
d={100:”shashi”,200:”nishi”,300:”shishir”}
print(d.keys())
for k in d.keys():
print(k)
Output
dict_keys([100, 200, 300])
100
200
300
values(): It returns all values associated with the dictionary
Ex:
d={100:”shashi”,200:”nishi”,300:”shishir”}
print(d.values())
for v in d.values():
print(v)
Output
dict_values([‘shashi’, ‘nishi’, ‘shishir’])
shashi
nishi
shishir
items():
It returns list of tuples representing key-value pairs.
[(k,v),(k,v),(k,v)]
Ex:
d={100:”shashi”,200:”nishi”,300:”shishir”}
for k,v in d.items():
print(k,”–“,v)
Output
100 — shashi
200 — nishi
300 — shishir
copy(): To create exactly duplicate dictionary(cloned copy) d1=d.copy();
setdefault():
d.setdefault(k,v)
- If the key is already available then this function returns the corresponding value.
- If the key is not available then the specified key-value will be added as new item to the dictionary.
Ex:
d={100:”shashi”,200:”nishi”,300:”shishir”}
print(d.setdefault(400,”manisha”))
print(d)
print(d.setdefault(100,”alok”))
print(d)
Output
manisha
{100: ‘shashi’, 200: ‘nishi’, 300: ‘shishir’, 400: ‘manisha’}
shashi
{100: ‘shashi’, 200: ‘nishi’, 300: ‘shishir’, 400: ‘manisha’}
update():
d.update(x)
All items present in the dictionary x will be added to dictionary d