Transforming a dict to another structure in Python

  • A+

I have a dict like below:

{'activity_count': [10, 11, 12], 'type': ['all', 'paper', 'fpy']} 

I want to transform this dict into this form:

{'all': {'activity_count': 10}, 'paper': {'activity_count': 11}, 'fpy': {'activity_count': 12}} 

How can I solve this?

So far I tried this solution,

dic={"activity_count":[10,11,12],"type":["all","paper","fpy"]} in={} i=0 for val in dic['type']:     for v in dic['activity_count']:         if i== dic['activity_count'].index(v):             temp={}             temp['activity_count']=v             fin[val]=temp     i+=1 

It works as I expected, but it looks very ineffective way to achieve this task. Is there a way to solve this problem?


Here a try, here zip is used to get values from both lists and to assign each:

d = {'activity_count': [10, 11, 12], 'type': ['all', 'paper', 'fpy']} nd = {j:{'activity_count':i} for i, j in zip(d['activity_count'], d['type'])} print(nd) 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: