Advantages of Dictionary
Advantages of Dictionary
Dictionary
Python dictionary is an unordered collection of items. While other compound data types
have only value as an element, a dictionary has a key: value pair.
Advantages of Dictionary
Dictionaries are optimized to retrieve values when the key is known.
Dictionaries in a programming language is a type of data-structure used to store
information connected in someway.
# empty dictionary
my_dict = {}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
Result:
Jack
26
Ex:
my_dict = {'name':'Jack', 'age': 26}
# update value
my_dict['age'] = 27
# add item
my_dict['address'] = 'Downtown'
Result:
{'age': 27, 'name': 'Jack'}
{'age': 27, 'name': 'Jack', 'address': 'Downtown'}
7.5. Remove element to Dictionary
# create a dictionary
# Output: 16
print(squares.pop(4))
print(squares)
# Output: (1, 1)
print(squares.popitem())
print(squares)
del squares[5]
# Output: {2: 4, 3: 9}
print(squares)
squares.clear()
# Output: {}
print(squares)
del squares
# Throws Error
# print(squares)
7.6. Built-in Dictionary Functions & Methods
len() Method:
Variable Type:
cmp() Method:
Str(dict):
Check length:
released = {
"iphone" : 2007,
"iphone 3G" : 2008,
"iphone 3GS" : 2009,
"iphone 4" : 2010,
"iphone 4S" : 2011,
"iphone 5" : 2012
}
print len(released)
Test the Dictionary:
or
Result:
Key Found
Only Keys:
phones = released.keys()
print phones
pprint.pprint(released)
>>output:
('iphone', 2007)
('iphone 3G', 2008)
('iphone 3GS', 2009)
('iphone 4', 2010)
('iphone 4S', 2011)
('iphone 5', 2012)
"""
or
>>output:
iphone 2007
iphone 5 2012
iphone 4 2010
iphone 3G 2008
iphone 4S 2011
iphone 3GS 2009
Counting:
count = {}
for element in released:
count[element] = count.get(element, 0) + 1
print count
>>output:
{'iphone 3G': 1, 'iphone 4S': 1, 'iphone 3GS': 1, 'iphone': 1,
'iphone 5': 1, 'iphone 4': 1}
7.7 Summary:
Method Description
Return a new dictionary with keys from seq and value equal
fromkeys(seq[, v])
to v (defaults to None).
Return the value of key. If key doesnot exit, return d(defaults
get(key[,d])
to None).
Remove the item with key and return its value or d if key is not found.
pop(key[,d])
If d is not provided and key is not found, raises KeyError.
Remove and return an arbitary item (key, value). Raises KeyError if the
popitem()
dictionary is empty.
If key is in the dictionary, return its value. If not, insert key with a value
setdefault(key[,d])
of d and return d (defaults to None).
Update the dictionary with the key/value pairs from other, overwriting
update([other])
existing keys.
Result: