Chapter : Dictionary
l A collection in python which is known as Dictionary
l Python dictionary is an 1 collection of items where each item is a key-value pair.
l We can also refer to a dictionary as a mapping between a set of keys/indices and a set of values.
l {}
Syntax:
{“key”:”values”}
{“key1”:Values”,“key2”:”values2” }
One items: “Keys”:”Values”
IMPORTANT FEATURES OF DICTIONARY ARE:
1. Each key map to a values.The association of a key and value is called a key-values pair.
2. Each key is separated from its value by a colon(:) , the items are separated by commas, and the entire dictionary is enclosed in curly braces.
3. Keys are unique within a dictionary while values may not be .
4. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as. strings, numbers, or tuple.
5. Dictionary is mutable. we can add new items or change the value of existing items.
Creating a Dictionary:
Syntax:
<Dic_name>={‘key1’:’value1’,’key2’:’value2’,’key3’:’value3’}
>>> a={"one":10,"two":20}
>>> a
{'one': 10, 'two': 20}
>>> a={"one":10,"one":20}
>>> a
{'one': 20}
>>> >>> a={"one":10,"two":20,1:"three",10:345,3:34.25}
>>> a
{'one': 10, 'two': 20, 1: 'three', 10: 345, 3: 34.25}
>>>
Empty Dictionary:
>>> dic={}
>>> dic
{}
>>> type(dic)
<class 'dict'>
>>> a=dict()
>>> a
{}
>>> >>> a={"one":10,"two":20,1:"three",10:345,3:34.25}
>>> a[0]
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
a[0]
KeyError: 0
>>> a[one]
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
a[one]
NameError: name 'one' is not defined
>>> a["one"]
10
>>> a[34]
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
a[34]
KeyError: 34
>>> a["34"]
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
a["34"]
KeyError: '34'
>>> a[3]
34.25
>>>
Creating an Empty dictionary:
>>> a={}
>>> a[1]="ONE"
>>> a
{1: 'ONE'}
>>> a[2]="TWO"
>>> a
{1: 'ONE', 2: 'TWO'}
>>> a[3]=30
>>> a
{1: 'ONE', 2: 'TWO', 3: 30}
>>>
Traversing a Dictionary
dic={1:"one",2:20,3:"three"}
for i in dic:
print(i,":",dic[i])
Appending values to a dictionary
We can add new elements to the existing dictionary, extend it with single pair of values or join two dictionaries into one. If we want to add only one element to the dictionary then we should use the following methods.
Syntax:
Dictionary_Name[Key]=values
Example:
>>> d1={'mon':"MONDAY",'tue':"TUESDAY",'wed':"WENESDAY"}
>>> d1['thu']="THURSDAY"
>>> d1
{'mon': 'MONDAY', 'tue': 'TUESDAY', 'wed': 'WENESDAY', 'thu': 'THURSDAY'}
>>> d1['fri']="FRIDAY"
>>> d1
{'mon': 'MONDAY', 'tue': 'TUESDAY', 'wed': 'WENESDAY', 'thu': 'THURSDAY', 'fri': 'FRIDAY'}
>>>
Updating Elements in a Dictionary
You can also update a dictionary by modifying existing key-values pair or by merging another dictionary with an existing one
Syntax:
Dictionary_Name[‘key’]=’Values’
>>> d2={'Teena':18,'Riya':12,'Alya':22}
>>> d2
{'Teena': 18, 'Riya': 12, 'Alya': 22}
>>> d2['Alya']=10
>>> d2
{'Teena': 18, 'Riya': 12, 'Alya': 10}
>>>
>>> d1={1:"one",2:"two"}
>>> d2.update(d1)
>>> d2
{'Teena': 18, 'Riya': 12, 'Alya': 10, 1: 'one', 2: 'two'}
>>> d1
{1: 'one', 2: 'two'}
>>> d3={100:"String"}
>>> d2.update(d1)
>>> d2
{'Teena': 18, 'Riya': 12, 'Alya': 10, 1: 'one', 2: 'two'}
>>> d2.update(d3)
>>> d2
{'Teena': 18, 'Riya': 12, 'Alya': 10, 1: 'one', 2: 'two', 100: 'String'}
Removing an item from Dictionary
We can remove an item from the existing dictionary by using del command or using pop() method
1. Using del command
Syntax:
del dicname[key]
Example:
>>> d1={1:100,2:200,3:"three",23.34:[1,2,3]}
>>> del d1[23.34]
>>> d1
{1: 100, 2: 200, 3: 'three'}
>>> del d1[2]
>>> d1
{1: 100, 3: 'three'}
>>> del d1[100]
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
del d1[100]
KeyError: 100
>>>
2. Using pop() method
Pop() method will not only delete the item from the dictionary but also returns the deleted value.
Syntax:
dictname.pop(key)
Example:
>>> d1
{1: 100, 3: 'three'}
>>> d1.pop(1)
100
>>> d1
{ 3: 'three'}
‘in’ and ‘not in’ Membership operator
The “in” operator checks whether a particular key is there in the dictionary.it returns true if elements appears in the dictionary, otherwise returns false.
Example:
>>> d1={1:100,2:200,3:"three",23.34:[1,2,3]}
>>> d1
{1: 100, 2: 200, 3: 'three', 23.34: [1, 2, 3]}
>>> 1 in d1
True
>>> 200 in d1
False
>>> "three" in d1
False
>>> 23.34 in d1
True
>>> 1 not in d1
False
>>>
COMMAN DICTIONARY FUNCTIONAS AND METHODS
1. len() --> count the element
This method returns number of key-values pair in the given dictionary.
Syntax:
len(dictionary_name)
Example:
>>> d1={1:100,2:200,3:"three",23.34:[1,2,3]}
>>> len(d1)
4
>>>
2. clear()
It removes all items from the particular dictionary
Syntax:
d1.clear()
Example:
>>> d1
{1: 100, 2: 200, 3: 'three', 23.34: [1, 2, 3]}
>>> d1.clear()
>>> d1
{}
>>>
3. get()
The get method returns a values for the give . If key is not available then returns default value None.
Syntax
d1.get(key,default=None)
Key: This is the key to be searched in the dictionary.
Default: this is a value to be returned in case the does not exist.
For Example:
>>> d1={'sun':'SUNDAY','mon':'MONDAY','tue':'TUESDAY'}
>>> d1
{'sun': 'SUNDAY', 'mon': 'MONDAY', 'tue': 'TUESDAY'}
>>> d1.get('sun')
'SUNDAY'
>>> d1.get('sun',default=None)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
d1.get('sun',default=None)
TypeError: get() takes no keyword arguments
>>> d1.get('fri')
>>> d1
{'sun': 'SUNDAY', 'mon': 'MONDAY', 'tue': 'TUESDAY'}
>>> d1.get('fri',default=None)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
d1.get('fri',default=None)
TypeError: get() takes no keyword arguments
>>> d1.get('fri','never')
'never'
>>> d1.get('mon','never')
'MONDAY'
>>> d1.get('fri',None)
>>> d1
{'sun': 'SUNDAY', 'mon': 'MONDAY', 'tue': 'TUESDAY'}
>>>
4. items()
It returns the content of the dictionary as a list of tuples having key-values pairs.
Syntax:
d1.items()
For example:
>>> d1
{'sun': 'SUNDAY', 'mon': 'MONDAY', 'tue': 'TUESDAY'}
>>> d1.items()
dict_items([('sun', 'SUNDAY'), ('mon', 'MONDAY'), ('tue', 'TUESDAY')])
>>>
5. keys()
It returns a list of the key values in a dictionary
Syntax:
d1.keys()
For example:
>>> d1
{'sun': 'SUNDAY', 'mon': 'MONDAY', 'tue': 'TUESDAY'}
>>> d1.keys()
dict_keys(['sun', 'mon', 'tue'])
>>>
6. values()
It returns a list of values from key-value pairs in a dictionary
Syntax:
d1.values()
For example:
>>> d1
{'sun': 'SUNDAY', 'mon': 'MONDAY', 'tue': 'TUESDAY'}
>>> d1.values()
dict_values(['SUNDAY', 'MONDAY', 'TUESDAY'])
>>>
7. fromkeys()
This function used to create a dictionary from a collection of keys(tuple/list))
Syntax:
d1=dict.fromkeys(<ck>,<v>)
For example:
>>> keys1=[1,2,3];values1=1000
>>> d1=dict.fromkeys(keys1,values1)
>>> d1
{1: 1000, 2: 1000, 3: 1000}
>>> keys2=[1,2,3];values2="Undefined"
>>> d1=dict.fromkeys(keys2,values2)
>>> d1
{1: 'Undefined', 2: 'Undefined', 3: 'Undefined'}
>>> keys2=[1,2,3]
>>> d1=dict.fromkeys(keys2)
>>> d1
{1: None, 2: None, 3: None}
>>>
8. copy()
This method creates a copy of a dictionary
Syntax:
d1.copy()
For Example:
>>> d1
{1: None, 2: 'strings', 3: None}
>>> d1[2]=2900
>>> d1
{1: None, 2: 2900, 3: None}
>>> d2
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
d2
NameError: name 'd2' is not defined
>>> d2=d1.copy()
>>> d2
{1: None, 2: 2900, 3: None}
>>>
9. popitem()
This method removes last items from the dictionary and returns this deleted item.
Syntax:
d2.popitem()
For example:
>>> d2
{1: None, 2: 2900, 3: None}
>>> d2.popitem()
(3, None)
>>> d2
{1: None, 2: 2900}
>>>
10. setdefault()
This method returns the values of the item with the specified key. if the key does not exits.it inserts the key with the specified values.
Syntax:
<Value>=<Dict>.setdefalut(<key>,<default_values>)
The set default returns:
1.Values of the key,if is in the dictionary
2.None,if key is not in the dictionary and default_values is not specified
3.Default_values,if keys is not in the dictionary and default values is specified.
For example:
>>> d={'Name':"Athishta","Gender":"Female"}
>>> a=d.setdefault('Name')
>>> a=d.setdefault('Name',"Name not available")
>>> a
'Athishta'
>>> a=d.setdefault('Gender',"Gender not available")
>>> a
'Female'
>>> a=d.setdefault('Age',"Age not available")
>>> a
'Age not available
>>>
11. max() and min()
This method max() returns key having maximum values. On the contrary, min() returns key having minimum values.
Syntax:
max(d1)
d1={"a":100,"b":50,"c":85,"d":65}
>>> max(d1)
'd'
>>> min(d1)
'a'
>>> chr("a")
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
chr("a")
TypeError: an integer is required (got type str)
>>> ord("a")
97
>>> ord("d")
100
>>> max(d1.values())
100
>>> min(d1.values())
50
>>> max(d1.items())
('d', 65)
>>> min(d1.items())
('a', 100)
>>> min(d1)
'a'
>>>
12. sorted()
This method sorted the elements of a dictionary by its key or values.
Syntax:
sorted(d1)
For example:
>>> d1={"a":100,"b":50,"c":85,"d":65}
>>> a=sorted(d1)
>>> a
['a', 'b', 'c', 'd']
d={"a":10,"b":20,"d":90,"c":100}
>>> x=sorted(d)
>>> x
['a', 'b', 'c', 'd']
>>> x=sorted(d.values())
>>> y=sorted(d.values())
>>> y
[10, 20, 90, 100]
>>> z=sorted(d.items())
>>> z
[('a', 10), ('b', 20), ('c', 100), ('d', 90)]
Download PDF
0 Comments