Louis
Louis

Reputation: 127

Convert value from dict to list in a dictionary: value is type list to value is type dictionary

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

Answers (3)

Rakesh
Rakesh

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

akash karothiya
akash karothiya

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

Ajax1234
Ajax1234

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

Related Questions