Python [Post 06] | Dictionary

Python dictionary is an un-ordered collection of items. It consists of a key value pairs.

  • Python dictionary is un-ordered & cannot be sorted.
  • Value can be almost any Python object.
  • Value can be accessed by unique key in the dictionary.
  • Keys must be of an immutable data type. Example – strings, numbers or tuples.

Creating a dictionary is as simple as placing items inside curly braces {} separated by comma. An item has a key and the corresponding value expressed as a pair, key: value.

{‘key1′:’value1′,’key2′:’value2’}

# Examples of Python Dictionary:

# Dictionary having string keys & string value
my_dict0 = { "N": "North", "S": "South", "E": "East", "W": "West" }

# Dictionary having integer keys & string value
my_dict1 = { 1: 'North', 2: 'South', 3: 'East', 4: 'West'}

# Dictionary having string keys & integer value
my_dict2 = { 'North' : 1, 'South': 2, 'East': 3,'West':4}

# Dictionary having mixed keys & values
my_dict3 = { 'N' : 'North', 2: 'South', 'East': 3,'West':'W', "ComplexNumber":5+500j, 5.5:[1,2,3,4]}

# Nested Dictionary
my_dict4 = { 'Aphabets' : { 'A':{'Fruit':'Apple','Object':'Aeroplane'},'B':{'Fruit':'Banana','Object':'Ball'}} ,
'Numbers' : { 0: 'Zero', 1:'One', 2:'Two', 3:'Three', 4:'Four', 5:'Five', 6:'Six', 7:'Seven'}
}
print(my_dict0)
print(my_dict1)
print(my_dict2)
print(my_dict3)
print(my_dict4)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}
{1: ‘North’, 2: ‘South’, 3: ‘East’, 4: ‘West’}
{‘North’: 1, ‘South’: 2, ‘East’: 3, ‘West’: 4}
{‘N’: ‘North’, 2: ‘South’, ‘East’: 3, ‘West’: ‘W’, ‘ComplexNumber’: (5+500j), 5.5: [1, 2, 3, 4]}
{‘Aphabets’: {‘A’: {‘Fruit’: ‘Apple’, ‘Object’: ‘Aeroplane’}, ‘B’: {‘Fruit’: ‘Banana’, ‘Object’: ‘Ball’}}, ‘Numbers’: {0: ‘Zero’, 1: ‘One’, 2: ‘Two’, 3: ‘Three’, 4: ‘Four’, 5: ‘Five’, 6: ‘Six’, 7: ‘Seven’}}

Other way to create dictionary to use the dict() constructor to make a dictionary:

sides = dict(N="North", S="South", E="East",W="West")
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}

Access elements from a dictionary

# Fetching dictionary values by key

print(sides['N'])
print(sides.get('S'))

North
South

# Nested Dictionary
my_dict = { 'Aphabets' : { 'A':{'Fruit':'Apple','Object':'Aeroplane'},'B':{'Fruit':'Banana','Object':'Ball'}} ,
'Numbers' : { 0: 'Zero', 1:'One', 2:'Two', 3:'Three', 4:'Four', 5:'Five', 6:'Six', 7:'Seven'}
}

smy_dict['Aphabets']['A']['Object']

‘Aeroplane’

my_dict4['Numbers'][5]

‘Five’

In Python dictionary no duplicate key is allowed.

# Creating a dictionary having duplicate keys

sides ={ "N": "East", "S": "South", "N": "West", "N": "North" }
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’}

When duplicate keys found during dictionary creation, the last assignment is final one. See above example.

### Updating Dictionary

Adding a new key-value pair, modifying an existing key-value pair, or deleting an existing key-value pair.

# Creating a new dictionary

sides = dict(N="North", S="South", E="East",W="West")
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}

Adding a new key:value pairs to existing dictionary

sides['NE'] = 'North-East'
sides['NW'] = 'North-West'
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’, ‘NE’: ‘North-East’, ‘NW’: ‘North-West’}

Updating key:value pair

sides['NE'] = 'North East'
sides['NW'] = 'North West'
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’, ‘NE’: ‘North East’, ‘NW’: ‘North West’}

sides['NE']

‘North East’

Deleting an existing key:value pair

print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’, ‘NE’: ‘North East’, ‘NW’: ‘North West’}

del sides ['N'] # Remove the provided Key
print(sides)

{‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’, ‘NE’: ‘North East’, ‘NW’: ‘North West’}

del sides ; # delete dictionary completely

### Dictionary Methods

Python Dictionary provides so many methods. See below some examples

sides = dict(N="North", S="South", E="East",W="West")
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}

Get()

It return Value for Key.

print(sides.get('S'))

South

Items(), Keys () & Value()

Item – It return the list with all dictionary keys with values.
Keys – It return list of dictionary dict’s keys.
Value – It returns list of dictionary dict’s values.

print(sides.items())
print(sides.keys())
print(sides.values())

dict_items([(‘N’, ‘North’), (‘S’, ‘South’), (‘E’, ‘East’), (‘W’, ‘West’)])
dict_keys([‘N’, ‘S’, ‘E’, ‘W’])
dict_values([‘North’, ‘South’, ‘East’, ‘West’])

Copy()

It creates the copy of the dictionary into other dictionary.

new_sides = {}
new_sides = sides.copy()
print(new_sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}

Update()

Adds dictionary key-values pairs to another dictionary.

sides = dict(N="North", S="South", E="East",W="West")
some_more_sides = dict(NE="North-East", SE="South-East")

print(sides)
print(some_more_sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}
{‘NE’: ‘North-East’, ‘SE’: ‘South-East’}

sides.update(some_more_sides)
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’, ‘NE’: ‘North-East’, ‘SE’: ‘South-East’}

Clear()

Removes all elements of dictionary.

some_more_sides.clear(); # Remove all entries in dictionary
print(some_more_sides)

{}


Thanks!

Happy Learning! Your feedback would be appreciated!

shobhitsingh.in

Github Code Link

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s