Dictionary
Dictionary
>>> new_dict = {}
>>> print(new_dict)
{}
>>> color
>>>
>>> dict[1]
20.5
>>> dict[3]
23.22
>>> 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
>>>print(dic)
{'pdy1': 'DICTIONARY'}
>>> print(dic)
>>>
>>> print(d)
>>> d.update({2:30})
>>> print(d)
>>>
Code:
d = {'Red': 1, 'Green': 2, 'Blue': 3}
Output:
>>>
Green corresponds to 2
Red corresponds to 1
Blue corresponds to 3
>>>
Remove a key from a Python dictionary
Code:
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
Code:
color_dict = {'red':'#FF0000',
'green':'#008000',
'black':'#000000',
'white':'#FFFFFF'}
Output:
>>>
black: #000000
green: #008000
red: #FF0000
white: #FFFFFF
>>>
Find the maximum and minimum value of a Python dictionary
Code:
my_dict = {'x':500, 'y':5874, 'z': 560}
Output:
>>>
Maximum Value: 5874
Minimum Value: 500
>>>
Concatenate two Python dictionaries into a new one
Code:
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
print(dic4)
Output:
>>>
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
>>>
Test whether a Python dictionary contains a specific key
Code:
fruits = {}
fruits["apple"] = 1
fruits["mango"] = 2
fruits["banana"] = 4
# Use in.
if "mango" in fruits:
print("Has mango")
else:
print("No mango")
if "orange" in fruits:
print("Has orange")
else:
print("No orange")
Output
>>>
Has mango
No orange
>>>
Find the length of a Python dictionary
Code:
fruits = {"mango": 2, "orange": 6}
print("Length:", len(fruits))
Output:
>>>
Length: 2
>>>