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?
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.
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.
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.
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.
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)
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.
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"))}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With