Getting a List of Values from a List of Dicts

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 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())

How to get values from a list of dictionaries, which themselves contain lists of dictionaries in Python

First: dict's require a key-value association for every element in the dictionary. Your 2nd level data structure though does not include keys: ({[{'tag': 'tag 1'}]}) This is a set. Unlike dict's, set's do not have keys associated with their elements. So your data structure looks like List[Set[List[Dict[str, str]]]].

Second: when I try to run

# python 3.8.8
player_info = [{[{'tag': 'tag 1'}]},
{[{'tag': 'tag 2'}]}]

I recieve the error TypeError: unhashable type: 'list'. That's because you're code attempts to contain a list inside a set. Set membership in python demands the members to be hashable. However, you will not find a __hash__() function defined on list objects. Even if you resolve this by replacing the list with a tuple, you will find that dict objects are not hashable either. Potential solutions include using immutable objects like frozendict or tuple, but that is another post.

To answer your question, I have reformulated your problem as

player_info = [[[{'tag': 'tag 1'}]],
[[{'tag': 'tag 2'}]]]

and compared the performance difference with A) explicit loops:

for i in range(len(player_info)):
print(player_info[i][0][0]['tag'])

against B) list comprehension

[
print(single_player_info[0][0]['tag'])
for single_player_info in player_info
]

Running the above code blocks in jupyter with the %%timeit cell magic, I got:
A) 154 µs ± 14.6 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each) and
B) 120 µs ± 11 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

Note: This experiment is highly skewed for at least two reasons:

  1. I tested both trials using only the data you provided (N=2). It is very likely that we would observe different scaling behaviors than initial conditions suggest.
  2. print consumes a lot of time and makes this problem heavily subject to the status of the kernel

I hope this answers your question.

Extract dict value from list of dict?

You can use a list comprehension:

ids = [y['id'] for y in x]

This assumes that every dictionary has a key 'id'. If you're not sure that key exists in every dictionary, you can use this one:

ids = [y['id'] for y in x if 'id' in y]

Get all values of list of dictionaries

You can do that with list comprehension:

count = [{'A': 0}, {'B': 2}, {'C': 4}]
[j for i in count for j in i.values()]

Output:

[0, 2, 4]

Get value from key within nested Lists of Dicts

The elegant solution will be to use jmespath
Also it will also handle the cases where key doesnot exist

pip install jmespath

If you have data as correct dictionary then we can use

import jmespath
expression = jmespath.compile('details[*].scorecardDetails[*].scorecard.playerHandicap')
# this expression will look in each detail then each scorecardDetails then in each scorecard it will fetch playerHandicap
res = expression.search(data)
print(res) # this will print the list of values from all records


Related Topics



Leave a reply



Submit