Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transforming a dict to another structure in Python

Tags:

python

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?

like image 205
Mohamed Thasin ah Avatar asked Jul 24 '18 08:07

Mohamed Thasin ah


People also ask

Can you modify dict in Python?

Modifying a value in a dictionary is pretty similar to modifying an element in a list. You give the name of the dictionary and then the key in square brackets, and set that equal to the new value.

Should I use dict () or {}?

With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.

How do I convert a dictionary to Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

What does dict values () return in Python?

The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.


3 Answers

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)
like image 182
Vikas Periyadath Avatar answered Oct 14 '22 07:10

Vikas Periyadath


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.

like image 30
Bierbarbar Avatar answered Oct 14 '22 08:10

Bierbarbar


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"))}
like image 25
whackamadoodle3000 Avatar answered Oct 14 '22 06:10

whackamadoodle3000