10

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?

1
  • 3
    {type_: {'activity_count': count} for count, type_ in zip(dic['activity_count'], dic['type'])}?
    – jonrsharpe
    Jul 24, 2018 at 8:33

3 Answers 3

11

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)
1
  • 2
    Instead of zip(d['activity_count'], d['type']) you can use zip(*d.values()).
    – Rahul K P
    Aug 31, 2018 at 7:21
6

I would go for zip and dict comprehension:

test = {'activity_count': [10, 11, 12], 'type': ['all', 'paper', 'fpy']}
solution = {key:{'activity_count':value} for value, key in zip(test["activity_count"],test["type"])}

Explanation: The zip of your two list groups the elements of the two list by with identical index. So it will convert your lists to a generator where the values are like this: [(10, 'all'), (11, 'paper'), (12, 'fpy')]. But the generator is lazy evaluated, so the tuples are only processed, when the dict comprehension asks for them, this saves memory.

The dict comprehension just iterates over this generator and puts the second element as key and the first one as value.

2
  • 2
    Almost. Needs key:{'activity_count':value} rather than key:value to generate what was requested.
    – Dan D.
    Jul 24, 2018 at 10:16
  • 1
    Oh yeah i was in rush, when i wrote the code. Thanks good catch, edited the answer.
    – Bierbarbar
    Jul 24, 2018 at 10:19
2

You could try this dictionary comprehension using enumerate:

dictionary = {'activity_count': [10, 11, 12], 'type': ['all', 'paper', 'fpy']}
{e:{"activity_count":dictionary.get("activity_count")[c]} for c,e in enumerate(dictionary.get("type"))}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.