Dictionary: Get List of Values for List of Keys

Dictionary: Get list of values for list of keys

A list comprehension seems to be a good way to do this:

>>> [mydict[x] for x in mykeys]
[3, 1]

How can I get list of values from dict?

dict.values returns a view of the dictionary's values, so you have to wrap it in list:

list(d.values())

Getting a list of values from a list of dicts

Assuming every dict has a value key, you can write (assuming your list is named l)

[d['value'] for d in l]

If value might be missing, you can use

[d['value'] for d in l if 'value' in d]

How do I extract all the values of a specific key from a list of dictionaries?

If you just need to iterate over the values once, use the generator expression:

generator = ( item['value'] for item in test_data )

...

for i in generator:
do_something(i)

Another (esoteric) option might be to use map with itemgetter - it could be slightly faster than the generator expression, or not, depending on circumstances:

from operator import itemgetter

generator = map(itemgetter('value'), test_data)

And if you absolutely need a list, a list comprehension is faster than iterated list.append, thus:

results = [ item['value'] for item in test_data ]

How to convert a list of keys and a list of value lists to a single list of dictionaries?

Try a simple list comprehension:

>>> keys = ['id','firstname','lastname']
>>> values = [[23,'abc','gef'],[24,'aabb','ppqq']]
>>> [dict(zip(keys, value)) for value in values]
[{'id': 23, 'firstname': 'abc', 'lastname': 'gef'}, {'id': 24, 'firstname': 'aabb', 'lastname': 'ppqq'}]

How to return dictionary keys as a list in Python?

This will convert the dict_keys object to a list:

list(newdict.keys())

On the other hand, you should ask yourself whether or not it matters. It is Pythonic to assume duck typing -- if it looks like a duck and it quacks like a duck, it is a duck. The dict_keys object can be iterated over just like a list. For instance:

for key in newdict.keys():
print(key)

Note that dict_keys doesn't support insertion newdict[k] = v, though you may not need it.

Dictionary - How to map list of KEY with list of VALUE?

Do this to get the desired result,

dictionary = dict(zip(key, value))

How make list of dict from list of keys and values from list of lists

keys=['number','type']
values=[[1,2,3,4],['bool','int','float','double']]

newList = []
for i in range(len(values[0])):
tmp = {}
for j, key in enumerate(keys):
tmp[key] = values[j][i]

newList.append(tmp)

print(newList)

Output:

[{'number': 1, 'type': 'bool'}, {'number': 2, 'type': 'int'}, {'number': 3, 'type': 'float'}, {'number': 4, 'type': 'double'}]

tip for future: you can use enumerate(list) instead of using i = i+1 or i += 1



Related Topics



Leave a reply



Submit