Reputation: 77
I have a python dictionary as follows:
A = {7: [21, 29, 43], 16: [20, 21, 37, 49], 21: [7, 16, 43], 29: [2, 7], 43: [7, 21], 46: [23, 36]}
I want to distribute the key to every element in the value list and create new list of tuples as follows:
B = [(7,21), (7,29), (7,43), (16,20),...]
How may I achieve this? Any help would be appreciated.
Upvotes: 0
Views: 530
Reputation: 6090
A = {7: [21, 29, 43], 16: [20, 21, 37, 49], 21: [7, 16, 43], 29: [2, 7], 43: [7, 21], 46: [23, 36]}
a = []
for key, values in A.items():
for value in values:
a.append((key,value))
print (a)
Output:
[(7, 21), (7, 29), (7, 43), (16, 20), (16, 21), (16, 37), (16, 49), (21, 7), (21, 16), (21, 43), (29, 2), (29, 7), (43, 7), (43, 21), (46, 23), (46, 36)]
Or, using list comprehension:
a = [(key,value) for key, values in A.items() for value in values]
Upvotes: 2