You can use itertools.product
for this, i.e calculate cartesian product of the value and then simply zip each of the them with the keys from the dictionary. Note that ordering of a dict's keys()
and corresponding values()
remains same if it is not modified in-between hence ordering won't be an issue here:
>>> from itertools
import product
>>>
my_dict = {
'A': [1, 2],
'B': [1, 4]
} >>>
keys = list(my_dict) >>>
[dict(zip(keys, p)) for p in product( * my_dict.values())]
[{
'A': 1,
'B': 1
}, {
'A': 1,
'B': 4
}, {
'A': 2,
'B': 1
}, {
'A': 2,
'B': 4
}]
you can use itertools.product
function within a list comprehension :
>>> from itertools
import product
>>>
[dict(i) for i in product( * [
[(i, k) for k in j]
for i, j in my_dict.items()
])]
[{
'A': 1,
'B': 1
}, {
'A': 1,
'B': 4
}, {
'A': 2,
'B': 1
}, {
'A': 2,
'B': 4
}]
You can get the pairs contain your key and values with the following list comprehension :
[(i, k) for k in j]
for i, j in my_dict.items()]
[
[('A', 1), ('A', 2)],
[('B', 1), ('B', 4)]
]
With itertools:
>>> from itertools
import product
>>>
my_dict = {
'A': [1, 2],
'B': [1, 4]
} >>>
keys, items = zip( * my_dict.items()) >>>
[dict(zip(keys, x)) for x in product( * items)]
[{
'A': 1,
'B': 1
}, {
'A': 1,
'B': 4
}, {
'A': 2,
'B': 1
}, {
'A': 2,
'B': 4
}]
Try this:
from itertools
import product
def dict_product(values, first, second):
return [{
first: first_value,
second: second_value
}
for first_value, second_value in product(values[first], values[second])
]
This is the result:
>>> dict_product({
'A': [1, 2],
'B': [1, 4]
}, 'A', 'B')[{
'A': 1,
'B': 1
}, {
'A': 1,
'B': 4
}, {
'A': 2,
'B': 1
}, {
'A': 2,
'B': 4
}]
Last Updated : 28 Nov, 2018
Original key list is: ['Rash', 'Kil', 'Varsha']
Original value list is: [1, 4, 5]
Resultant dictionary is: {
'Varsha': 5,
'Rash': 1,
'Kil': 4
}
Original key list is: ['Rash', 'Kil', 'Varsha']
Original value list is: [1, 4, 5]
Resultant dictionary is: {
'Varsha': 5,
'Kil': 4,
'Rash': 1
}
Original key list is: ['Rash', 'Kil', 'Varsha']
Original value list is: [1, 4, 5]
Resultant dictionary is: {
'Kil': 4,
'Rash': 1,
'Varsha': 5
}
dict() is a built-in function. If used without parameter, it creates an empty dictionary. The function uses a list of two item tuples as parameter.The new dictionary object is constructed with each tuple treated as key-value pair.,items(), keys() and values() methods return view objects that are lists of k:v pairs, keys and values respectively. Any change in composition of dictionary will automatically reflect in these view objects.,update() method merges two dictionaries by updating values with common keys in both and adding items with new keys from another dictionary.,To update the dictionary, just assign a new value to existing key. If the key is not currently used, a new key-value pair is added to dictionary.
Some examples of dictionary objects are shown below:
In[1]:
capitals = {
"Maharashtra": "Mumbai",
"Telangana": "Hyderabad",
"Tamilnadu": "Chennai",
"Karnataka": "Bengaluru",
"Bihar": "Patna"
}
rankings = {
1: "India",
2: "England",
3: "South Africa",
4: "Australia",
5: "New Zealand"
}
prices = {
"pen": 25,
"bike": 50000,
"mobile": 5000,
"book": 250
}
In[2]:
print("state capitals:", capitals)
print("Team rankings:", rankings)
print("prices:", prices)
Out[2]:
state capitals: {
'Maharashtra': 'Mumbai',
'Telangana': 'Hyderabad',
'Tamilnadu': 'Chennai',
'Karnataka': 'Bengaluru',
'Bihar': 'Patna'
}
Team rankings: {
1: 'India',
2: 'England',
3: 'South Africa',
4: 'Australia',
5: 'New Zealand'
}
prices: {
'pen': 25,
'bike': 50000,
'mobile': 5000,
'book': 250
}
In [3]:
manufacturers={("Nokia", "Samsung","MicroMax"):"Mobiles", ("Nike", "Adidas", "Puma"):"Sports Goods",
("Honda","Bajaj", "TVS"):"Bikes"}
sports={"indoors":["chess", "Badminton", "Table Tennis"], "outdoor":["Cricket", "Football", "Rugby"]}
In [4]:
animals={["snake", "Lizard"]:"reptiles", ["Parrot", "Crow"]:"birds"}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-1904d3d80b08> in <module>()
----> 1 animals={["snake", "Lizard"]:"reptiles", ["Parrot", "Crow"]:"birds"}
TypeError: unhashable type: 'list'
To update the dictionary, just assign a new value to existing key. If the key is not currently used, a new key-value pair is added to dictionary.
In[8]:
ChiefMinisters = {
"Maharashtra": "Fadanvis",
"UP": "Yogi",
"Karnataka": "KumarSwamy",
"MP": "chauhan"
}
ChiefMinisters["MP"] = "KamalNath"
ChiefMinisters["Maharashtra"] = "Thakre"
ChiefMinisters
Out[8]: {
'Maharashtra': 'Thakre',
'UP': 'Yogi',
'Karnataka': 'KumarSwamy',
'MP': 'KamalNath'
}
In[9]:
ChiefMinisters["Delhi"] = "Kejriwal"
ChiefMinisters
Out[9]: {
'Maharashtra': 'Thakre',
'UP': 'Yogi',
'Karnataka': 'KumarSwamy',
'MP': 'KamalNath',
'Delhi': 'Kejriwal'
}
dict() is a built-in function. If used without parameter, it creates an empty dictionary. The function uses a list of two item tuples as parameter.The new dictionary object is constructed with each tuple treated as key-value pair.
In[13]:
d1 = dict()
d1
Out[13]: {}
In[14]:
dict([(1, 100), (2, 200), (3, 300)])
Out[14]: {
1: 100,
2: 200,
3: 300
}
In[15]:
dict(a = 1, b = 2, c = 3)
Out[15]: {
'a': 1,
'b': 2,
'c': 3
}
items(), keys() and values() methods return view objects that are lists of k:v pairs, keys and values respectively. Any change in composition of dictionary will automatically reflect in these view objects.
In[16]:
CMs = {
'Maharashtra': 'Thakre',
'UP': 'Yogi',
'Karnataka': 'KumarSwamy',
'MP': 'KamalNath',
'Delhi': 'Kejriwal'
}
CMs.items()
Out[16]:
dict_items([('Maharashtra', 'Thakre'), ('UP', 'Yogi'), ('Karnataka', 'KumarSwamy'), ('MP', 'KamalNath'), ('Delhi', 'Kejriwal')])
In[17]:
CMs.keys()
Out[17]:
dict_keys(['Maharashtra', 'UP', 'Karnataka', 'MP', 'Delhi'])
In[18]:
CMs.values()
Out[18]:
dict_values(['Thakre', 'Yogi', 'KumarSwamy', 'KamalNath', 'Kejriwal'])
In[19]:
CMs.pop("UP")
Out[19]:
'Yogi'