简体   繁体   中英

Is there a better way to get dict values in a dict list?

I have a list like this:

[{'enter_time': '2021-03-01 07:15:16', 'leave_time': '2021-03-01 07:16:06'}, {'enter_time': '2021-03-02 08:15:16', 'leave_time': '2021-03-02 08:16:06'}]

As you can see, every item in the list is a dict. Now, I wanna get a new list consisting of all enter_time and leave_time . I should get a new list like this:

>>> new_list
>>> ['2021-03-01 07:15:16', '2021-03-01 07:16:06', '2021-03-02 08:15:16', '2021-03-02 08:16:06']

I have tried in a awkward way:

datetime_str_list = [{'enter_time': '2021-03-01 07:15:16', 'leave_time': '2021-03-01 07:16:06'}, {'enter_time': '2021-03-02 08:15:16', 'leave_time': '2021-03-02 08:16:06'}]
new_list = []
for item in datetime_str_list:
    for dict_value in item.values():
        new_list.append(dict_value)
print('new_list', new_list)

I have no idea how to implement this in a elegant way. Looking forward to your solutions.

This should work:

times = [{'enter_time': '2021-03-01 07:15:16', 'leave_time': '2021-03-01 07:16:06'}, 
        {'enter_time': '2021-03-02 08:15:16', 'leave_time': '2021-03-02 08:16:06'}]

Explicit approach

I start by creating a list to hold the results ( new_times ). For each item in the original list called times , we extract the values associated with each of the two keys: enter_time and leave_time .

We can reference each of these using the syntax item['enter_time'] OR item['leave_time'] .

The .extend() method of the Python list object allows us to extend a list by adding multiple items to the end of the list (as compared to the `.append() method which only adds one item at a time).

new_times = list()
for item in times:
    new_times.extend([item['enter_time'], item['leave_time']])

With that, new_times should yield:

['2021-03-01 07:15:16',
 '2021-03-01 07:16:06',
 '2021-03-02 08:15:16',
 '2021-03-02 08:16:06']

More concise approach (and probably more Pythonic approach)

If there is no benefit to explicitly referencing the individual elements of item, we can simply reference them all by calling for the .values associated with each item dictionary.

new_times = list()
for item in times:
     new_times.extend(item.values())

Nested List Comprehension approach:

There is the ability to do this with nested comprehensions, but that may come at the cost of readability.

new_times_lc = [value for subdict in times for value in subdict.values()]

Basically, this is equivalent to a nested for loop.

for a list comprehension approach:

new_list = [list(d.values()) for d in old_list]
flat_list = [i for sublist in new_list for i in sublist]

This will assign all values in the original dictionaries into a list of lists, and then flatten that list into a 1D list of all the values

Using the map function:

from itertools import chain

times = [{'enter_time': '2021-03-01 07:15:16', 'leave_time': '2021-03-01 07:16:06'}, {'enter_time': '2021-03-02 08:15:16', 'leave_time': '2021-03-02 08:16:06'}]

new_times = list(chain(*list(map(lambda x: list(x.values()), times))))

This gets the values from each dictionary and unpacks them, similarly to the list comprehensions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM