Q-1.Write a Python program to map two lists into a dictionary.
Input: keys = ['red', 'green', 'blue'] values = ['#FF0000','#008000', '#0000FF'] Output:{'red': '#FF0000', 'green': '#008000', 'blue': '#0000FF'}
Python Code:
#map two list into dictionary keys = ['red', 'green', 'blue'] values = ['#FF0000','#008000', '#0000FF'] color_code=dict(zip(keys,values)) print(color_code)
Q-2.Write a Python program to check whether a given key already exists in a dictionary.
Input: d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} Output: Key is present in the dictionary Key is not present in the dictionary
Python Code:
#key exists or not in dictionary d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} def is_key_present(x): if x in d: print('Key is present in the dictionary') else: print('Key is not present in the dictionary') is_key_present(5) is_key_present(9)
Q-3.Write a Python program to match key values in two dictionaries.
Input: x = {'key_1': 1, 'key_2': 3, 'key_3': 2} y = {'key_1': 1, 'key_2': 2}
Output:key_1: 1 is present in both x and y
Python Code:
#match key values in two dictionaries. x = {'key_1': 1, 'key_2': 3, 'key_3': 2} y = {'key_1': 1, 'key_2': 2} for (key, value) in set(x.items()) & set(y.items()): print('%s: %s is present in both x and y' % (key, value))
Q-4.Write a Python program to get the key, value and item in a dictionary
Input: dict_num = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} Output: key value count 1 10 1 2 20 2 3 30 3 4 40 4 5 50 5 6 60 6
Python Code:
#To get the key, value and item in a dictionary dict_num = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} print("key value count") for count, (key, value) in enumerate(dict_num.items(), 1): print(key,' ',value,' ', count)
Q-5.Write a Python program to concatenate following dictionaries to create a new one.
Input: dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60}
Output:{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
Python Code:
#concatenate the dictionaries 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)
0 Comments