Home > front end >  Converting values in dictionary in to another dictionary using python
Converting values in dictionary in to another dictionary using python

Time:05-11

I have a set of dictionaries with keys and values i need all the values as a separate dictionary

print(i)
O/P:
{'type':a,total:3}
{'type':b,total:2}
{'type':c,total:5}
{'type':d,total:6}

But now the required Output should like this...

{'a':3}
{'b':2}
{'c':5}
{'d':6}

CodePudding user response:

You can use something like this:

dictionaries = ({'type':'a','total':3},
            {'type':'b','total':2},
            {'type':'c','total':5},
            {'type':'d','total':6},)

for _dict in dictionaries:
    _type, total = _dict.values()
    print({_type : total})

CodePudding user response:

Given the following input:

dicts = [{'type':'a','total':3},
         {'type':'b','total':2},
         {'type':'c','total':5},
         {'type':'d','total':6}]

You can try using a list comprehension like this:

[{x:y for x,y in [d.values()]} for d in dicts]

Output:

[{'a': 3}, {'b': 2}, {'c': 5}, {'d': 6}]
  • Related