Open In App

Python dictionary with keys having multiple inputs

Last Updated : 27 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Python-Dictionary

How to create a dictionary where a key is formed using inputs? 

Let us consider an example where have an equation for three input variables, x, y, and z. We want to store values of equation for different input triplets.

Example 1:

Python3




# Python code to demonstrate a dictionary
# with multiple inputs in a key.
import random as rn
 
# creating an empty dictionary
dict = {}
 
# Insert first triplet in dictionary
x, y, z = 10, 20, 30
dict[x, y, z] = x + y - z;
 
# Insert second triplet in dictionary
x, y, z = 5, 2, 4
dict[x, y, z] = x + y - z;
 
# print the dictionary
print(dict)


Output

{(10, 20, 30): 0, (5, 2, 4): 3}

Time complexity: O(1) for each insertion and O(n) for printing the dictionary where n is the number of key-value pairs.
Auxiliary space: O(n) to store the dictionary.

Python dictionary with keys having multiple inputs to get access to the keys. 

Let us consider a dictionary where longitude and latitude are the keys and the place to which they belong to is the value.

Python3




# dictionary containing longitude and latitude of places
places = {("19.07'53.2", "72.54'51.0"):"Mumbai", \
          ("28.33'34.1", "77.06'16.6"):"Delhi"}
 
print(places)
print('\n')
 
# Traversing dictionary with multi-keys and creating
# different lists from it
lat = []
long = []
plc = []
for i in places:
    lat.append(i[0])
    long.append(i[1])
    plc.append(places[i[0], i[1]])
 
print(lat)
print(long)
print(plc)


Output

{("19.07'53.2", "72.54'51.0"): 'Mumbai', ("28.33'34.1", "77.06'16.6"): 'Delhi'}


["19.07'53.2", "28.33'34.1"]
["72.54'51.0", "77.06'16.6"]
['Mumbai', 'Delhi']

Time complexity: O(n), where n is the number of keys in the dictionary.
Auxiliary space: O(n), where n is the number of keys in the dictionary .

Now that the keys(latitude, longitude) and values(place) are stored in a list, we can access it easily.

Python dictionary with keys having multiple inputs

The idea behind this code is to create a dictionary with multiple inputs for keys. In this case, the keys are tuples with three elements: an integer, a first name, and a last name. The values associated with each key are themselves dictionaries with three key-value pairs.

The code creates the dictionary and then accesses the values associated with certain keys using indexing. It also demonstrates how to modify the values associated with certain keys using the same indexing notation.

Step-by-step approach to implementing this code:

  • Start by defining a dictionary variable named “data”.
  • Inside the curly braces, define each key-value pair using a tuple as the key and a dictionary as the value. Separate each key-value pair with a comma.
  • Inside each tuple key, include three elements: an integer, a first name, and a last name. Separate each element with a comma.
  • Inside each dictionary value, include three key-value pairs. The keys can be any string or integer, and the values can be any data type.
  • To access a value in the dictionary, use indexing with the key tuple. For example, to print the value associated with the key (1, “John”, “Doe”) and the key “a”, use the notation “data[(1, “John”, “Doe”)][“a”]”.
  • To modify a value in the dictionary, use indexing with the key tuple and then assign the new value using the equals sign. For example, to change the value associated with the key (1, “John”, “Doe”) and the key “a”, use the notation “data[(1, “John”, “Doe”)][“a”] = {“b”: “marketing”, “c”: 75000}”.
  • Print the modified value to verify the change.

Python3




# Creating a dictionary with multiple inputs for keys
data = {
    (1, "John", "Doe"): {"a": "geeks", "b": "software", "c": 75000},
    (2, "Jane", "Smith"): {"e": 30, "f": "for", "g": 90000},
    (3, "Bob", "Johnson"): {"h": 35, "i": "project", "j": "geeks"},
    (4, "Alice", "Lee"): {"k": 40, "l": "marketing", "m": 100000}
}
 
# Accessing the values using the keys
print(data[(1, "John", "Doe")]["a"])
print(data[(2, "Jane", "Smith")]["f"])
print(data[(3, "Bob", "Johnson")]["j"])
 
data[(1, "John", "Doe")]["a"] = {"b": "marketing", "c": 75000};
data[(3, "Bob", "Johnson")]["j"] = {"h": 35, "i": "project"};
print(data[(1, "John", "Doe")]["a"]);
print(data[(3, "Bob", "Johnson")]["j"]);


Output

geeks
for
geeks
{'b': 'marketing', 'c': 75000}
{'h': 35, 'i': 'project'}

Time complexity: O(1), where the hash function used to map the key to a bucket in the dictionary allows for constant-time access in most cases.
Auxiliary space: O(n), where each key and value takes up a constant amount of memory, the space complexity of the data dictionary is O(1) for the keys. 



Previous Article
Next Article

Similar Reads

How to Take Multiple Inputs Using Loop in Python
Taking multiple inputs in Python is a common task, especially when dealing with user interactions or processing data sets. Using a for loop can simplify the process and make the code more efficient. In this article, we will explore simple and commonly used methods to take multiple inputs in Python using loops in Python. Take Multiple Inputs Using L
3 min read
Taking multiple inputs from user in Python
The developer often wants a user to enter multiple values or inputs in one line. In C++/C user can take multiple inputs in one line using scanf but in Python user can take multiple values or inputs in one line by two methods.  Methods to Take multiple inputs from user Using split() method :Using map() with split():Using List comprehension : Using s
4 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Python - Append Dictionary Keys and Values ( In order ) in dictionary
Given a dictionary, perform append of keys followed by values in list. Input : test_dict = {"Gfg" : 1, "is" : 2, "Best" : 3} Output : ['Gfg', 'is', 'Best', 1, 2, 3] Explanation : All the keys before all the values in list. Input : test_dict = {"Gfg" : 1, "Best" : 3} Output : ['Gfg', 'Best', 1, 3] Explanation : All the keys before all the values in
5 min read
Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
Python | Check if given multiple keys exist in a dictionary
A dictionary in Python consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value. Input : dict[] = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3} keys[] = {"geeksforgeeks", "practice"} Output : Yes Input : dict[] = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3} keys[] = {"geeksforgeeks", "
3 min read
Python | Remove multiple keys from dictionary
While working with Python dictionaries, we can have a utility in which we require to remove more than one key at once. This type of problem can occur while working in the Web Development domain with NoSQL Databases. Let's discuss certain ways in which this task can be performed. Remove multiple keys from a dictionary using del Here, we are using a
6 min read
Python | Initialize dictionary with multiple keys
Sometimes, while working with dictionaries, we might have a problem in which we need to initialize the dictionary with more than one key with the same value. This application requirement can be in domains of web development in which we might want to declare and initialize simultaneously. Let's discuss certain ways in which this task can be performe
8 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Python - Extract selective keys' values Including Nested Keys
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys' values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records. This problem caters all the nestings for extraction of keys' values. Let's discuss certain w
7 min read