skip to Main Content

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}

2

Answers


  1. 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})
    
    Login or Signup to reply.
  2. 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}]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search