Python dictionary multiple keys

In this Python tutorial, we will discuss what the Python dictionary multiple keys are and how to create a dictionary with multiple keys in Python. We will see how to get multiple keys in Dictionary Python and how to add multi-key Dictionary Python using different methods present in Python. We will also see the following subtopics and will explain with some illustrative 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

What is Python dictionary multiple keys

In Python, a dictionary is a collection of key-value pairs where each key must be unique. We can have a Python dictionary with multiple keys in it.

Example 1: Let’s create a dictionary in Python with multiple keys using curly braces{}. Take some states and their capitals as the key-value pair for the dictionary.

state_capitals = {
    'California': 'Sacramento',
    'Texas': 'Austin',
    'New York': 'Albany',
    'Florida': 'Tallahassee',
    'Illinois': 'Springfield'
}
print(state_capitals)
print(type(state_capitals))
python dictionary with multiple keys

This is how we can create a Python dictionary with multiple keys using curly braces{}.

Note: We can also use dict() constructor or dictionary comprehension method in Python to create a dictionary with multiple keys.

Example 2: By using the for loop method we can check every value contained 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 in Python with multiple keys then we create an empty Python dictionary in which the result has been stored in the form of a key-value pair. When looping through that Python dictionary, the return value is the key of that Python 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:\n",new_dict)

Here is the execution of the following given code:

Create dictinary with multiple keys:
 {'micheal': 6, 'George': 6, 'Oliva': 6}
dictionary with two keys python
Python dictionary multiple keys

How to add multiple keys in Python dictionary

In Python, dictionaries are mutable collections of items(key-value pair), i.e., We can manipulate data stored inside the Python dictionary using different methods. Let’s see some examples:

To Create a dictionary with multiple keys and then add multiple key-value pairs to it at a time we can use the update() method or dictionary unpacking(*) in Python:

Example 2: Let’s take a scenario, where we are building a system to store state capitals for a USA geography quiz application. We initially starts with a few states and their capitals. As we gather more data, we want to add more states and their capitals to our dictionary in Python.

state_capitals = {
    'California': 'Sacramento',
    'Texas': 'Austin'
}
new_capitals = {
    'Florida': 'Tallahassee',
    'Georgia': 'Atlanta'
}
state_capitals.update(new_capitals)
print(state_capitals)

Output: With the update() method, we’ve successfully added multiple new states (keys) and their capitals (values) to the original state_capitals dictionary in Python.

{'California': 'Sacramento', 'Texas': 'Austin', 'Florida': 'Tallahassee', 'Georgia': 'Atlanta'}
python dictionary with two keys

Note : We can also unpack using (*) and concatenate using (+), these two dictionaries.

Example 2: To Create a Python 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.

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 Python list and then use map string values to an object. As you can see the output will display that every key contains its own value which is [1,2,3] and hence, we have created a dictionary through Python.

Here is the execution of the following given code:

python dictionary two keys one value
python dictionary two keys one value
Python dictionary multiple keys methods

By using tuples with multiple keys of dictionary in Python

  • Here we can see how to use the Python tuple concept while creating a dictionary with multiple keys in Python.
  • To do this particular task first we will initialize an empty Python 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'
print(my_dict)

new_key=('Country','Name')
if new_key in my_dict:
    print( my_dict[new_key] )

Here is the Screenshot of the following given code:

python dictionary with 2 keys
Python dictionary multiple keys

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 Python dictionary.
  • Here we can use the concept of dict.keys() method that will return an object that displays a dictionary in Python of all the keys which is present in the Python 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 Python 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:

python dict with multiple keys
Python dictionary multiple keys same value

Check multiple keys in dictionary with same value in Python

In this example, we can apply the concept of the dict comprehension method. In Python, the dictionary comprehension method is to create a dictionary by merging two sets of data which are in the form of Python 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 Python 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 Python list.

Here is the output of the following given code:

python multi key dictionary
Python dictionary multiple keys same value

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 in Python methods.
  • Here we create a Python 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 Python.
  • Now initialize an empty Python dictionary and use the concept of for loop to iterate over the Python 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:

python dictionary 2 keys
Python dictionary multiple keys with the same name

As you can see from the Output, the multiple keys have the same name in a Python dictionary.

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 Python dictionary or not. To declare a for loop method use items to iterate through a Python 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 Python 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 from a Dictionary in Python.

Here is the Output of the following given code:

Python dictionary multiple keys
Python dictionary multiple keys get

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 Python 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 Python dict 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:

Python dictionary with multiple keys
Python dictionary multiple key values

Python dictionary multiple key levels

  • Here we can see how to get multiple key levels from the dictionary in Python.
  • To solve this problem we can use the concept of the defaultdict() method to get multiple key levels. In Python, the defaultdict() 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 With open() function in Python. For this, you also 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 Python code:

python dictionary select multiple keys
Python dictionary multiple key levels
Python dictionary with two keys

As you can see the output it displays multiple keys level in the form of a dictionary in Python.

Python dictionary two keys

  • Let us see how to combine two keys and get multiple key-value in Python dictionary.
  • Here we create a Python 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 Python list.
  • In this example, you can use any object as a key and contains a value in the form of a list in Python dict.

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:

python dict multiple keys
Python dict with two keys

Conclusion

In this Python tutorial, we have discussed what the Python dictionary multiple keys are and how to create a dictionary with multiple keys in Python. We have also seen, how to get multiple keys in Dictionary Python and how to add multi-key Dictionary Python using different methods present in Python. We have used different methods present in Python like for loop, dictionary comprehension, update(), defaultdict(), etc. to get the desired output.

We have taken different demonstartive examples to better understand all the above mentioned concept in Python.

You may also like to read the following tutorials.

\"IT電腦補習
立刻註冊及報名電腦補習課程吧!

Find A Teacher Form:
https://docs.google.com/forms/d/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ/viewform?edit_requested=true#responses

Email:
public1989two@gmail.com






www.itsec.hk
www.itsec.vip
www.itseceu.uk

Be the first to comment

Leave a Reply

Your email address will not be published.


*