In this Python tutorial, we will discuss the Python dictionary multiple keys. Here we will also cover the below examples:
- Python dictionary multiple keys same value
- Python dictionary multiple keys with same name
- Python dictionary multiple keys at once
- Python dictionary multiple keys get
- Python dictionary multiple key values
- Python dictionary multiple key levels
- Python dictionary two keys
Python dictionary multiple keys
- Let us see how to create a Python dictionary with multiple keys.
- By using for loop method we can perform this particular task to check every value contains in the dictionary or not. To create a for loop use items to iterate through a dictionary of key-value pairs.
- In this example first, we will initialize a dictionary with multiple keys then we create an empty dictionary in which the result has been stored in the form of key-value pair. When looping through a dictionary, the return value is the key of the dictionary.
Source Code:
new_dict = {}
new_k = ['micheal', 'George', 'Oliva']
for org_key in new_k:
new_dict[org_key] = 6
print("Create dictinary with multiple keys:",new_dict)
Here is the execution of the following given code
Another way to check how to add multiple keys in Python dictionary
- Here we can see the alternative way to solve how to add multiple keys in Python dictionary.
- To Create a dictionary with multiple keys we can apply the mapped method with a single value and it allows a user to update the value at all keys at the same time.
Example:
new_lis = [1,2,3]
you_dict = {"John" : new_lis, "Potter" : new_lis}
print(you_dict)
In the above code first, we will initialize a list and then use map strings values to an object. As you can see the output will display that every key contains its own value which is [1,2,3].
Here is the execution of the following given code
By using tuples with multiple keys
- Here we can see how to use the tuple concept while creating a dictionary with multiple keys.
- To do this particular task first we will initialize an empty dictionary and then use values in the form of tuples. In Python dictionary, tuples are hashable objects and can be used as a key or value. After that check the condition if ‘key’ contains in the given list or not.
Source Code:
my_dict={}
my_dict[('Country','Name')]='Germany'
my_dict[('Ipl','year')]='2014'
my_dict[('student','name')]='Elite'
new_key=('Country','Name')
if new_key in my_dict:
print( my_dict[new_key] )
Here is the Screenshot of the following given code
Read: Python find max value in a dictionary
Python dictionary multiple keys same value
- Let us see how to assign the same value to multiple keys in a dictionary.
- Here we can use the concept of dict.keys() method that will return an object that displays a dictionary of all the keys which is present in the tuple.
Source Code:
class new_dict(dict):
def keylist(self, new_k, new_val):
for n_key in new_k:
self[n_key] = new_val
b = new_dict()
b.keylist(('l', 'o', 'i'), 5)
print(b)
In the above code first, we will create a function ‘new_dict’ and assign a dictionary ‘dict’. Now use for loop method to iterate ‘keylist’ and display multiple keys with the same value.
Here is the execution of the following given code
Alternative way to check multiple keys in dictionary with same value
In this example, we can apply the concept of the dict comprehension method. In Python, the dictionary comprehension method is to create a dict by merging two sets of data which are in the form of lists.
you_dictionary = {
new_key: new_val
for keys, new_val in [(['y', 'q', 'x'], 40), (['i', 'l'], 40)]
for new_key in keys
}
print("Multiple keys same value:",you_dictionary)
In the above code first, we will initialize a dictionary and assign them a dictionary comprehension method as an argument. Now I have to store multiple Keys with the associated value and contains them in a list.
Here is the output of the following given code
Read: How to create an empty Python dictionary
Python dictionary multiple keys with same name
- In Python dictionary, if you want to display multiple keys with the same value then you have to use the concept of for loop and list comprehension method.
- Here we create a list and assign them a value 2 which means the keys will display the same name two times. After that declare a variable ‘new_val’ and assign them values in the form of a list.
- Now initialize an empty dictionary and use the concept of for loop to iterate a list and apply the list comprehension to allow you to create lists from existing lists.
Example:
new_lis = [2]
new_val = [[18, 21, 56], [14, 10, 61]]
my_new_dictionary = {}
for m in new_lis:
my_new_dictionary[m] = new_val
for key,val in my_new_dictionary.items():
for val in my_new_dictionary[key]:
print("new_key: {} :: same_nam_val: {}".format(key, val))
Here is the implementation of the following given code
As you can see from the Output, the multiple keys have the same name in a dictionary.
Read: Python Dictionary to CSV
Python dictionary multiple keys get
- Here we can see how to get multiple keys in a Python dictionary.
- To do this task we can use for loop method to check that every value contains in the dictionary or not. To declare a for loop method use items to iterate through a dictionary key-value pairs.
Example:
my_dict = {}
new_k = ['lichard', 'John', 'james']
for org_key in new_k:
my_dict[org_key] = 8
print("Get multiple keys with value:",my_dict)
In the above code first, we will create an empty dictionary and along with that declare a variable assign them a key list with the associated value that is 8. Now display the result and you can get multiple keys with values.
Here is the Output of the following given code
Read: Python convert dictionary to an array
Python dictionary multiple key values
- Let us see how to get multiple keys-values from Python dictionary.
- In this example, if you want to get multiple keys-values then you need to associate an object with each key as a value. In the given dict the keys are strings and with every single key, we assign a list of numbers as a value.
Source Code:
my_dict = {'n': [4,2,3,4],
'z': [18,23,45,7,],
'u': [78,34,5,6],
'q': [19,10,12,34],
'p': [446,76,5,9]}
new_val = my_dict['q']
print('Multiple Values of key "q" are:',new_val)
In the above Code, we choose an item from the dictionary where the key is ‘q’ and it will return all the values associate with the key.
Here is the execution of the following given code
Read: Python dictionary of tuples
Python dictionary multiple key levels
- Here we can see how to get multiple key levels from the dictionary.
- To solve this problem we can use the concept of the defaultdict() method to get multiple key levels. In Python, the default dict will simply create any items that you want to try access. The method always returns a dictionary-like object.
- Now if you want to open a file in the writing mode then you can use the open() function. For this, you need to import a CSV and collection module.
Source Code:
import collections
import csv
new_out = collections.defaultdict(int)
with open("test9.csv","rt") as f:
for line in f:
new_val = line.split()
new_key = '-'.join(new_val)
new_out[new_key] += 1
print (new_out)
Here is the Output of the following given code
As you can see the output it displays multiple keys level in the form of a dictionary.
Read: Python creates a dictionary from two lists
Python dictionary two keys
- Let us see how to combine two keys and get multiple key-value.
- Here we create a list and assign them a value 2 which means the keys will display the same name two times. After that declare a variable ‘new_val’ and assign them values in the form of a list.
- In this example, you can use any object as a key and contains a value in the form of a list.
Example:
lis1 = [2]
new_val2 = [[18, 21, 56], [14, 10, 61]]
you_dictionary = {}
for z in lis1:
you_dictionary[z] = new_val2
for key,val in you_dictionary.items():
for val in you_dictionary[key]:
print("new_key: {} :: same_nam_val: {}".format(key, val))
Here is the Output of the following given code
You may also like to read the following tutorials.
- Python dictionary pop
- Python loop through a list
- Python convert DataFrame to list
- Get First Key in dictionary Python
- Python dictionary increment value
- Python for loop index
- Python dictionary Copy
- Check if two dictionaries are equal in Python
In this Python tutorial, we have discussed the Python dictionary multiple keys. Here we have also covered the following examples:
- Python dictionary multiple keys same value
- Python dictionary multiple keys with same name
- Python dictionary multiple keys at once
- Python dictionary multiple keys get
- Python dictionary multiple key values
- Python dictionary multiple key levels
- Python dictionary multiple key types
- Python dictionary two keys
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.