Working with Dictionaries/Lists to Get List of Keys

Working with dictionaries/lists to get list of keys

Yes, the list type is a good approximation. You can use names() on your list to set and retrieve the 'keys':

> foo <- vector(mode="list", length=3)
> names(foo) <- c("tic", "tac", "toe")
> foo[[1]] <- 12; foo[[2]] <- 22; foo[[3]] <- 33
> foo
$tic
[1] 12

$tac
[1] 22

$toe
[1] 33

> names(foo)
[1] "tic" "tac" "toe"
>

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]

get keys and values from a Python dictionary as lists

Use List Comprehensions:

In [148]: P1 = [list(i.keys())[0] for i in T1]

In [149]: D1 = [list(i.values())[0] for i in T1]

In [150]: P1
Out[150]: [0, 15, 19, 20, 0]

In [151]: D1
Out[151]: [0, 3, 1, 1, 0]

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

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 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.

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.



Related Topics



Leave a reply



Submit