Reputation: 87
I am trying to solve some graph problems but i am stuck halfway. I have a python dictionary of sets, but i will like to convert the original dictionary values (which are sets) into a dictionary such that each value in the set becomes a key which would have another value of 1. I think this is what is called a nested dictionary - i am not sure.
I looped through the dict.values()
, assigned to a variable xxx, and used the dict.fromkeys(xxx, 1)
code and it worked, but i am unable to integrate the result back into the original dictionary.
Here is an example of a dictionary:
d = {'35': {'1', '37', '36', '71'}, '37': {'1', '35'}}
I want the output to look like:
d = {35: {1 : 1, 37 : 1, 36 : 1, 71 : 1}, 37: {1 : 1, 35 : 1}}
if you notice, the original dictionary values have become dictionaries of their own, and the apostrophes ('') are off.
Can someone assist me please, or give me pointers. Thank you
Upvotes: 3
Views: 954
Reputation: 6438
You just need a little bit of list comprehension:
def convert(input):
return {key: {val: 1 for val in vals} for key, vals in input.items()}
print(convert({'35': {'1', '37', '36', '71'}, '37': {'1', '35'}}))
# {'35': {'1': 1, '37': 1, '36': 1, '71': 1}, '37': {'1': 1, '35': 1}}
Upvotes: 1
Reputation: 29742
You are almost there. Just wrap keys and values with int
:
{int(k):dict.fromkeys(map(int, v), 1) for k, v in d.items()}
Output:
{35: {37: 1, 71: 1, 36: 1, 1: 1}, 37: {35: 1, 1: 1}}
Upvotes: 0