Python dictionary of tuples

In this Python tutorial, we will discuss the Python dictionary of tuples. Here we will also cover the below examples:

  • Python dictionary list of tuples
  • Python dictionary tuples as keys
  • Python dictionary vs tuples
  • Python dictionary tuple values
  • Python create dict of tuples
  • Python sort dictionary of tuples
  • Python dictionary of named tuples
  • Python unpack dictionary of tuples
  • How to add tuple as key in dictionary python
  • Python iterate dictionary tuple
  • Python iterate dictionary with tuple key
  • Python access tuple in dictionary
  • Python dictionary append tuple
  • Python dict to tuple array

Python dictionary of tuples

  • In Python to get all tuples from a dictionary, we can use the list comprehension method.
  • To create a list from iterable we can use the list comprehension method and terminate each element along with for loop to iterate each value.

Example:

Let’s take an example and check how to get keys and values in the form of tuples from a dictionary.

my_new_dic = { 'England': 435, 'France': 12, 'Egypt': 31 }

new_tup = [(key, value) for key, value in my_new_dic.items()]
print(new_tup)

In the above code first, we have created a dictionary and assign them key-value pair elements. Now declare a variable and use one single line of code that is the list comprehension method and it is converted into a list of tuples.

Here is the Screenshot of the following given code

Python dictionary of tuples
Python dictionary of tuples

Alternative example to check how to get tuples from a dictionary.

In this example, we will take a dict() function to get a dictionary from tuples. This method returns an iterable object and converts it into a dictionary form.

Source Code:

def Convert(new_tu, my_dict):
    my_dict = dict(new_tu)
    return my_dict
      
new_val = [("k", 167), ("z", 179), ("u", 179), 
    ("m", 267), ("a", 445), ("l", 134)]
new_dict = {}
print (Convert(new_val, new_dict))

Here is the execution of the following given code

Python dictionary of tuples using dict
Python dictionary of tuples using dict

Python dictionary list of tuples

  • Here we can see how to convert the list of tuples into a Python dictionary.
  • In this example, first we will initialize a list with tuples and use the dict() method to convert a list of tuples into a dictionary and print the result. It will display the output in the form of dictionary which contains key-value pair.
  • In Python the dict() method takes a list of tuples as an argument and each tuple store key-value pair element and it returns into a dictionary.

Source Code:

new_tup = [('g',19), ('n', 21), ('l', 17), ('q', 39), ('d', 55)]

new_res = dict(new_tup)
print(new_res)

Here is the Output of the following given code

Python dictionary list of tuples
Python dictionary list of tuples

Read: Python dictionary pop

Python dictionary tuples as key

  • Let us see how to get a tuple as a key from a Python dictionary.
  • To perform this particular task we can use the list comprehension method to iterate each dictionary element and get the tuples key that is available in the dictionary.
  • To access the tuple elements from the dictionary and contains them in a list. We have to initialize a dictionary and pass the tuple key and value as an argument. Now to get all tuple keys from the dictionary we have to use the Python list comprehension method.

Example:

to_dictionary = {(19, 25) : 'rose', (65, 47, 91) : 'lily', (57, 199) : 'Jasmine'}

new_output = [element for new_key in to_dictionary for element in new_key]
print("tuple key elements of dictionary are:",new_output)

Here is the Screenshot of the following given code

Python dictionary tuples as key
Python dictionary tuples as key

Read: Python creates a dictionary from two lists

Python dictionary vs tuples

  • The main difference between dictionaries and tuples are:
  • In Python, tuples are represented by comma and enclosed in parenthesis whereas dictionaries are represented by open curly brackets.
  • In the case of Python tuples, they are immutable which means you cannot change an existing element.
  • In Python dictionary, it is an unordered collection of data that contains elements in the form of key-value pair whereas a tuple is an ordered collection of data that contains simple characters or integers and is represented by commas.
  • In Python, the reverse() method cannot be used in tuples because they are immutable. we can use indexing and slicing methods. In the case of the dictionary, we cannot change or reverse the given elements because items in the dictionary are in the form of key-value pairs.

Source Code:

my_new_lis = [('o',67), ('m', 149), ('b', 190), ('c', 123), ('e', 55)]

new_res = dict(my_new_lis)
print(new_res) # dictionary example

new_tup = [4,9,12,'m']
print(tuple(new_tup)) # tuple example

In this example, we have initialized a list and contains the elements in the form of tuples. Now I want to convert this list into a dictionary to do this I will create a variable and use the dict() method to convert the list into a dictionary. After that, I will create a new list and use a print statement in which I will pass the ‘tuple’ keyword as an argument and display the result.

Here is the execution of the following given code

Python dictionary vs tuples
Python dictionary vs tuples

Read: Python dictionary contains

Python dictionary tuple values

  • Let us see how to get a tuple as a value from the dictionary.
  • To solve this problem we can use the list comprehension method to iterate each dictionary element and get the values of the tuple which is present in the dictionary.

Source Code:

you_dict = {(112, 189) : 'c', (192,981,278) : 'f', (176,156) : 'l'}

new_output = [element for new_value in you_dict for element in new_value]
print("tuple values elements of dictionary are:",new_output)

Here is the implementation of the following given code

Python dictionary tuple values
Python dictionary tuple values

Read: Python sort list of tuples

Python create dict of tuples

  • Here we can see how to create a dictionary by accessing tuples.
  • To do this task we will use the dict() method that helps the user to convert tuples into dictionaries. This method takes a tuple of tuples as a parameter and returns them into a dictionary form.

Example:

new_value = ((18, "m"), (169, "v"), (779, "x"), (189, "b"))

new_dict = dict((j, k) for k, j in new_value)
print("created dictionary",new_dict)

In the above code, we have to use the dict() method and pass the dictionary comprehension method as a parameter to declare a dictionary. As you can see in the screenshot the output gets the key-value pair elements.

Here is the output of the following given code

Python create dict of tuples
Python create dict of tuples

Read: Python concatenate tuples

Python sort dictionary of tuples

  • In Python to sort a dictionary by tuples, we can use the combination of dict(), sorted(), and lambda() function. In this example dict() method is used to rearrange the elements and reassigns the dictionary by order.
  • The Sort() method will help the user to sorts the elements of a given tuple in ascending or descending order and the lambda function is used to calculate the product according to the given values.

Source Code:

new_my_dict = {(34, 38) : 17, (13, 98) : 45, (43, 45): 19, (5, 10): 2}

new_out = dict(sorted(new_my_dict.items(), key = lambda element: element[0][1] * element[0][0]))
print("Sort dict by tuples:",new_out)

Here is the Screenshot of the following given code

Python sort dictionary of tuples
Python sort dictionary of tuples

Read: Python loop through a list

Python dictionary of named tuples

  • In Python namedtuple() is a built-in function under the category of collection module. To create tuple subclasses with the specific fields we can use the namedtuple() method.
  • This method can access both values and keys in a given named tuple. To create a namedtuple in Python we have to import a collection module.

Example:

import collections

employee = collections.namedtuple('emp_info',['emp_name','emp_age','emp_id'])
new_dict = { 'emp_name' : "Hayden", 'emp_age' : 26 , 'emp_id' : '1678' }
print ("nametuple from dict",employee(**new_dict))

In this example first, we will initialize a dictionary and contain elements in it. Now use the ** operator to return namedtuple() from the given dictionary.

Here is the execution of the following given code

Python dictionary of named tuples
Python dictionary of named tuples

Read: Python convert dictionary to list

Python unpack dictionary of tuples

In Python to unpack a dictionary and convert it into a tuple, we can use the tuple() method. Unpack means the fulfillment of a dictionary into a function call.

Source Code:

my_dictionary = {'George' : 17, 'John' : 19, 'Micheal' : 13}

new_val = tuple(my_dictionary)
print(new_val)

Here is the Screenshot of the following given code

Python unpack dictionary of tuples
Python unpack dictionary of tuples

Another example to check how to unpack dictionary elements into tuples

By using the ‘=’ operator and multiple variables we can easily solve this problem. In this example, we declare the comma-separated variables to the given dictionary and store them in a ‘count_dict’ variable.

Example:

count_dict = {'Afghanistan' : 19, 'colombia' : 14, 'srilanka' : 36}

z, l, m = count_dict
new_val_key = z, l, m
print(new_val_key)

Here is the output of the following given code

Python unpack dictionary of tuples method
Python unpack dictionary of tuples method

This is how to unpack dictionary keys into a tuple.

Read: Python dictionary remove

Python iterate dictionary tuple

In this section, we can see how to iterate over a dictionary in Python. In this example, the keys are a tuple and the values are integer numbers. Now we will use the dict() method and it accepts for loop instance over the list of tuples.

Source Code:

new_tup = dict({
  ('m', 'n'): 18,
  ('y', 'z'): 28
})

for new_key, new_val in new_tup.items():
   print("iterate dictionary:",new_key,  " - ", new_val)

Here is the implementation of the following given code

Python iterate dictionary tuple
Python iterate dictionary tuple

Read: Python dictionary length

Python iterate dictionary with tuple key

  • In Python to iterate through a dictionary with a tuple key, we can easily use a for loop method to access each element that is available in the dictionary.
  • In this example to iterate over the tuple key we can apply append method and pass ‘you_dict‘ as an argument. Now it will iterate over this list of tuples with the variable name ‘new_val’.

Source Code:

i, j, k = "i", "j", "k"
you_dict = {(17, i): 237, (17, k): 789, (19, j): 851}
new_val = list()

num = 0 
for i in you_dict:
    new_val.append(list(i[1])) 
    new_val[num].append(you_dict[i]) 
    num += 1
new_val = dict(new_val) 
print("iterate tuple keys",new_val)

Here is the Output of the following given code

Python iterate dictionary with tuple key
Python iterate dictionary with tuple key

Read: Python dictionary initialize

Python access tuple in dictionary

  • Let us see how to access a tuple in a Python dictionary.
  • Here I want to access tuple values in a dictionary. To do this task first I have to initialize a dictionary with a unique key and a tuple with three values. Now I want to iterate each key to do this we can use the item in the dict() method and this function does not take any argument. It always returns the list will all dictionary elements.

Source Code:

my_new_dictionary = {"zxy":(16,19,14), "ukh":(18,19,28), "loq":(15,19,23)}

for item in my_new_dictionary:
    print ("Access tuple values:",item[1])
    print (item[2])
    print (item[0])

Here is the execution of the following given code

Python access tuple in dictionary
Python access tuple in the dictionary

Read: Python Dictionary index

Python dictionary append tuple

  • Let us see how to add tuples that store multiple values to a single key in a Python dictionary.
  • In this example, you just map your key to a list and add tuples to the list. To perform this particular task we will create a dictionary and assign a key-value element but in this case, the value represents the list. Now declare a variable and use the append function to add a tuple in a dictionary.

Example:

student_dict = {'johnson': [(67,89,24)]}

b = student_dict['johnson'].append((123,173,992))
print("append tuple in dictionary",student_dict)

Here is the Screenshot of the following given code

Python dictionary append tuple
Python dictionary append a tuple

Read: Python Dictionary sort

Python dict to tuple array

  • Let us see how to convert a Python dictionary into the tuple array.
  • In this example, first we will create a dictionary and assign them key-value pair. Now declare a variable ‘new_arr‘ and pass new_key and new_val variable as a tuple argument. To convert dictionary into array of tuple we can use list comprehension method.

Source Code:

my_new_dict = { 'i': 189, 'o': 149, 'z': 216 }

new_arr = [(new_key, new_val) for new_key, new_val in my_new_dict.items()]
print("Dictionary to tuple array",new_arr)

Here is the Screenshot of the following given code

Python dict to tuple array
Python dict to tuple array

You may also like to read the following articles:

In this Python tutorial, we have discussed the Python dictionary of tuples. Here we have also covered the following examples:

  • Python dictionary list of tuples
  • Python dictionary tuples as keys
  • Python dictionary vs tuples
  • Python dictionary tuple values
  • Python create dict of tuples
  • Python sort dictionary of tuples
  • Python dictionary of named tuples
  • Python unpack dictionary of tuples
  • How to add tuple as key in dictionary python
  • Python iterate dictionary tuple
  • Python iterate dictionary with tuple key
  • Python access tuple in dictionary
  • Python dictionary append tuple
  • Python dict to tuple array