Reputation: 127
How can I convert from:
{'a': [2], 'b': [2], 'c': [1], 'd': [1]}
to
{'a': 2, 'b': 2, 'c': 1, 'd': 1}
I tried:
for key, value in numbersOfFollowersDict.items():
numbersOfFollowersDict[key] = dict(value)
print(numbersOfFollowersDict)
But error appear:
numbersOfFollowersDict[key] = dict(value)
TypeError: cannot convert dictionary update sequence element #0 to a sequence
Upvotes: 0
Views: 49
Reputation: 82765
Using dict()
d = {'a': [2], 'b': [2], 'c': [1], 'd': [1]}
d = dict((k, v[0]) for k,v in d.items())
print(d)
Output:
{'a': 2, 'c': 1, 'b': 2, 'd': 1}
Upvotes: 1
Reputation: 5950
You can dict comprehension
here
>>> d = {'a': [2], 'b': [2], 'c': [1], 'd': [1]}
>>> output = {k: v[0] for k, v in d.items()}
{'a': 2, 'c': 1, 'b': 2, 'd': 1}
Upvotes: 3
Reputation: 71451
You can use unpacking in a dictionary comprehension:
d = {'a': [2], 'b': [2], 'c': [1], 'd': [1]}
new_d = {a:b for a, [b] in d.items()}
Output:
{'a': 2, 'b': 2, 'c': 1, 'd': 1}
Upvotes: 3