Dictionaries in Python
Dictionaries in Python
The syntax provides useful type information. The square brackets indicate that its a
list. The parenthesis indicate that the elements in the list are tuples.
Iterate over Python dictionaries using for loops
d={'red':1,'green':2,'blue':3}
for k, v in d.items():
print(k,'corresponds to', v)
OUTPUT:
blue corresponds to 3
green corresponds to 2
red corresponds to 1
myDict = {'a':1,'b':2,'c':3,'d':4}
print(myDict)
if 'a' in myDict:
del myDict['a']
print(myDict)
OUTPUT:
d = {'red': 1,
'green': 2,
'black: 3,
'white': 4}
OUTPUT:
Black 3
Green 2
Red 1
white 4
Find the maximum and minimum value of a Python dictionary
key_max = max(my_dict.keys())
key_min = min(my_dict.keys())
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:
if "orange" in fruits:
print("Has orange")
else:
print("No orange")
OUTPUT:
Has mango
No orange
QUESTIONS
Q1:Write a Python script to add a key to a dictionary.
Q2: Write a Python script to concatenate following dictionaries to create a new one.
Sample Dictionary :
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
Q3: Write a Python script to check if a given key already exists in a dictionary.
Q4: Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and
the values are square of keys.
Sample Dictionary
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
Q6: Write a Python script to merge two Python dictionaries.
Q11: Write a Python program to create and display all combinations of letters, selecting each letter from a
different key in a dictionary.