Alphalearningschool
        

<<< Prev

Next >>>

Up
Python Dictionary

Python dictionary is a container of the unordered set of objects like lists. The objects are surrounded by curly braces { }. The items in a dictionary are a comma-separated list of key:value pairs where keys and values are Python data type.

Each object or value accessed by key and keys are unique in the dictionary. As keys are used for indexing, they must be the immutable type (string, number, or tuple). You can create an empty dictionary using empty curly braces. 

Create a new dictionary in Python

#Empty dictionary
 new_dict = dict()
 new_dict = {}
 print(new_dict)
{}
 #Dictionary with key-vlaue
 color = {"col1" : "Red", "col2" : "Green", "col3" : "Orange" }
 color
{'col2': 'Green', 'col3': 'Orange', 'col1': 'Red'}

 

Get value by key in Python dictionary

#Declaring a dictionary
 dict = {1:20.5, 2:3.03, 3:23.22, 4:33.12}
  #Access value using key
 dict[1]
20.5
 dict[3]
23.22
 #Accessing value using get() method
 dict.get(1)
20.5
 dict.get(3)
23.22

 

Add key/value to a dictionary in Python

#Declaring a dictionary with a single element
 dic = {'pdy1':'DICTIONARY'}
print(dic)
{'pdy1': 'DICTIONARY'}
 dic['pdy2'] = 'STRING'
 print(dic)
{'pdy1': 'DICTIONARY', 'pdy2': 'STRING'}

 #Using update() method to add key-values pairs in to dictionary
 d = {0:10, 1:20}
 print(d)
{0: 10, 1: 20}
>>> d.update({2:30})
>>> print(d)
{0: 10, 1: 20, 2: 30}

 

Iterate over Python dictionaries using for loops

Code:
d = {'Red': 1, 'Green': 2, 'Blue': 3} 
for color_key, value in d.items():
     print(color_key, 'corresponds to ', d[color_key])

Output:
Green corresponds to  2
Red corresponds to  1
Blue corresponds to  3

 

Remove a key from a Python dictionary

myDict = {'a':1,'b':2,'c':3,'d':4}
print(myDict)
if 'a' in myDict: 
    del myDict['a']
print(myDict)

Output:
{'d': 4, 'a': 1, 'b': 2, 'c': 3}
{'d': 4, 'b': 2, 'c': 3}

 

Sort a Python dictionary by key

color_dict = {'red':'#FF0000',
          'green':'#008000',
          'black':'#000000',
          'white':'#FFFFFF'}

for key in sorted(color_dict):
    print("%s: %s" % (key, color_dict[key]))


Output:
black: #000000
green: #008000
red: #FF0000
white: #FFFFFF

 

Find the maximum and minimum value of a Python dictionary

my_dict = {'x':500, 'y':5874, 'z': 560}

key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))

print('Maximum Value: ',my_dict[key_max])
print('Minimum Value: ',my_dict[key_min])


Output:
Maximum Value:  5874
Minimum Value:  500

 

Concatenate two Python dictionaries into a new one

dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
for d in (dic1, dic2, dic3): dic4.update(d)
print(dic4)
 

Output:
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

 

Test whether a Python dictionary contains a specific key

fruits = {}
fruits["apple"] = 1
fruits["mango"] = 2
fruits["banana"] = 4

# Use in.
if "mango" in fruits:
    print("Has mango")
else:
    print("No mango")
# Use in on nonexistent key.
if "orange" in fruits:
    print("Has orangerr")
else: b    
    print("No orange")


Output
Has mango
No orange

 

Find the length of a Python dictionary

fruits = {"mango": 2, "orange": 6}
# Use len() function 
#to get the length of the dictionary
print("Length:", len(fruits))

                                                                                                                                                                                             
Output: 
Length: 2

 

 Sl no  

Methods of Dictonary with Description

   

1

dict.clear()

Removes all elements of dictionary dict

2

dict.copy()

Returns a shallow copy of dictionary dict

3

dict.fromkeys()

Create a new dictionary with keys from seq and values set to value.

4

dict.get(key, default=None)

For key key, returns value or default if key not in dictionary

5

dict.has_key(key)

Returns true if key in dictionary dictfalse otherwise

6

dict.items()

Returns a list of dict's (key, value) tuple pairs

7

dict.keys()

Returns list of dictionary dict's keys

8

dict.setdefault(key, default=None)

Similar to get(), but will set dict[key]=default if key is not already in dict

9

dict.update(dict2)

Adds dictionary dict2's key-values pairs to dict

10

dict.values()

Returns list of dictionary dict's values