Python Dictionary
Python dictionary is an
unordered collection of iteam.
Syntax
key : value
pair
How to create a dictionary ?
empty dictionary
my_dict = {}
dictionary with integer keys
my_dict = {1: 'One', 2: 'two'}
dictionary with mixed keys
my_dict = {'name': 'Arun',1:'semester','marks': [45,67,89]}
using dict()
my_dict = dict({1: 'One', 2:'Two'})
from sequence having each item as a pair
my_dict = dict([(1,'One'), (2,'Two')])
How to access elements from a dictionary?
my_dict = {'name':'Ram', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))
output
Ram
26
How to change or add element in a dictionary?
my_dict = {'name':'Ram', 'age': 26}
update value
my_dict['age'] = 27
print(my_dict)
my_dict['address'] = 'Madurai'
print(my_dict)
output
{'name':'Ram', 'age': 27}
{'name':'Ram', 'age': 27, 'address':
'madurai'}
How to delete or remove element from a
dictionary ?
create a dictionary
squares = { 1:1, 2:4, 3:9, 4:16, 5:25}
print(squares.pop(4))
remove a particular item
Output: 16
print(squares)
Output: { 1: 1, 2: 4, 3: 9, 5: 25}
print (squares.popitem())
Output: (1, 1)
print (squares)
Output: {2: 4, 3: 9, 5: 25}
del squares[5]
print(squares)
Output:{2: 4, 3: 9}
squares.clear()
print(squares)
Output: {}
del squares
print(squares)
#Throws Error
OUTPUT
16
{ 1: 1, 2: 4, 3: 9, 5: 25}
(1, 1)
{2: 4, 3: 9, 5: 25}
{2: 4, 3: 9}
{}
Python Dictionary Methods
Method |
Dictionary |
clear() |
Remove all items from the dictionary. |
copy() |
Return a shallow copy of the dictionary. |
fromkeys(seq[, v]) |
Return a new dictionary with keys from seq and
value equal to v (defaults to none). |
get(key[,d]) |
Return the value of key. if key dosenot exit,
return d(defaluts to none). |
items() |
Return a new view of the dictionary's items(key,
value) |
keys() |
Return a new view of the dictionary's keys. |
pop(key[,d]) |
Remove the item with key and return
its value or d if key is not found. if d is not provided and key is not
found, raises keyerror. |
popitem() |
Remove and return an arbitary item (key, value).
raises keyerror If the dictionary is empty. |
setdefault(key[,d]) |
If key is in the dictionary, return its value. if
not, insert key with a value of d and return d (defaluts to none). |
update([other]) |
Update the dictionary with the key/value pairs
from other, overwriting existing keys. |
values() |
Return a new view of the dictionary's values |
marks = {}.fromkeys(['math','english','science'], 0)
print(marks)
Output: {'English': 0, 'math': 0,
'science': 0}
for item in marks.item():
print(item)
list(sorted(marks.keys()))
Output:
('science', 0)
('math', 0)
('english', 0)]
Python Dictionary Comprehension
squares = {x: x*x for x in range(6)}
print(squares)
Output:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Other Dictionary Operations
Dictionary Membership Test
num_squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(1 in num_squares) output:true
print(2 not in num_squares) output:true
print(49 in num_squares) output:false
lterating Through a Dictionary
Using for loop we can iterate though eeach key in a dictionary
cubes = {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
for i in cubes :
print (cubes[i])
OUTPUT
1
8
27
64
125
function |
Description |
all() |
Return true if all keys of the dictionary are
true (or if the dictionary empty) |
any() |
Return true if all 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 |
sorted() |
Return a new sorted list of keys in the
dictionary |
Built - in method
> > > dict2 = {'country': 'india','code':91 }
> > > dict2.has_key('country')
1
> > >
> > > dict2['country']
'india'
> > >
> > > dict2.has_key('number')
0
> > > dict2.keys()
['country', 'code']
> > >
> > > dict2.values()
[91, 'india']
> > >
> > > dict2.items()
(['code',91), ('country', 'india')]
> > >
> > > for eachkey in dict2.keys():
... print 'dict2 key', eachkey, 'has valus',
dict2[eachkey]
...
> > > dict2keys = dict2.keys()
> > > dict2keys.sort()
> > > for eachkey in dict2keys:
... print 'dict2 key', eachkey, 'has value',
dict2 [eachkey]
...
dict2 key country has value india
dict2 key code has value 91
0 comments:
Post a Comment