Python Dictionary

python dictionary

What is Python Dictionary?

A python dictionary consists of keys and values. It is helpful to compare a dictionary to a list. Instead of the numerical indexes such as a list, dictionaries have keys. These keys are the keys that are used to access values within a dictionary.

It is very simple to create a dictionary as placing items inside {} separated by , commas.

Each item will have a KEY and a corresponding VALUE consecutively, it will look like {Key:Value}.

While the values can be of any data type and can repeat, keys must be of immutable type and must be unique.

In [59]:

# This is example of Dictonary 
Dict = {"A" : 1, "B" : 2, "Key3" : 3, "Key4" : 4}
Dict

Out[59]:

{'A': 1, 'B': 2, 'Key3': 3, 'Key4': 4}

In [76]:

#Access Dictionary Values
Dict ["A"]

Out[76]:

1

Dict [(0,1)]

Each key is separated from its value by a colon “:”. Commas separate the items, and the whole dictionary is enclosed in curly braces. An empty python dictionary without any items is written with just two curly braces, like this “{}”.

In [86]:

# Create a sample dictionary

Name_Age_Dict = {"Umair": "1985", "Simmi": "1980", \
                    "Moon": "1973", "Sumaira": "1992", \
                    "Ali": "1977", "Asghar": "1976", \
                    "Tahira": "1977", "Fatima": "1977"}
Name_Age_Dict
#capital letter effects the results.

Out[86]:

{'Umair': '1985',
 'Simmi': '1980',
 'Moon': '1973',
 'Sumaira': '1992',
 'Ali': '1977',
 'Asghar': '1976',
 'Tahira': '1977',
 'Fatima': '1977'}

In [87]:

# Get value by key

Name_Age_Dict['Tahira'] 

Out[87]:

'1977'

In [88]:

# Get all the keys in dictionary

Name_Age_Dict.keys() 

Out[88]:

dict_keys(['Umair', 'Simmi', 'Moon', 'Sumaira', 'Ali', 'Asghar', 'Tahira', 'Fatima'])

In [89]:

# Get all the values in dictionary

Name_Age_Dict.values() 

Out[89]:

dict_values(['1985', '1980', '1973', '1992', '1977', '1976', '1977', '1977'])

In [91]:

# Append value with key into dictionary

Name_Age_Dict ['Tahira'] = '1992'
Name_Age_Dict

Out[91]:

{'Umair': '1985',
 'Simmi': '1980',
 'Moon': '1973',
 'Sumaira': '1992',
 'Ali': '1977',
 'Asghar': '1976',
 'Tahira': '1992',
 'Fatima': '1977',
 'Graduation': '2007'}

In [92]:

# Delete entries by key

del(Name_Age_Dict['Ali'])
Name_Age_Dict

Out[92]:

{'Umair': '1985',
 'Simmi': '1980',
 'Moon': '1973',
 'Sumaira': '1992',
 'Asghar': '1976',
 'Tahira': '1992',
 'Fatima': '1977',
 'Graduation': '2007'}

In [93]:

#verify
'Ali' in Name_Age_Dict

Out[93]:

False

In [94]:

#verify
'Umair' in Name_Age_Dict

Out[94]:

True

In [13]:

V={'A','B'}
V.add('C')
V

Out[13]:

{'A', 'B', 'C'}

In [19]:

A = {'1','2'} 
a=set(A)
a

Out[19]:

{'1', '2'}

In [20]:

type(set([1,2,3]))

Out[20]:

set

In [21]:

{'a','b'} &{'a'}

Out[21]:

{'a'}

Python Dictionary Methods

Methods that are available with a dictionary are tabulated below. Some of them have already been used in the above examples.

MethodDescription
clear()Removes all items from the dictionary.
copy()Returns a shallow copy of the dictionary.
fromkeys(seq[, v])Returns a new dictionary with keys from seq and value equal to v (defaults to None).
get(key[,d])Returns the value of the key. If the key does not exist, returns d (defaults to None).
items()Return a new object of the dictionary’s items in (key, value) format.
keys()Returns a new object of the dictionary’s keys.
pop(key[,d])Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises KeyError.
popitem()Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty.
setdefault(key[,d])Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None).
update([other])Updates the dictionary with the key/value pairs from other, overwriting existing keys.
values()Returns a new object of the dictionary’s values

Leave a Comment