Eduardo G
Eduardo G

Reputation: 430

How to split one list of dicts into two lists of dicts by keys

I have the next dict:

# lists of dicts 0 (dict0)
[
 {'hour': '2:00', 'key1': 1, 'key2': 501},
 {'hour': '3:00', 'key1': 2, 'key2': 502},
 {'hour': '4:00', 'key1': 3, 'key2': 503},
 {'hour': '5:00', 'key1': 4, 'key2': 504},
]

How can I split (in a pythonic way) this list into two lists of dicts that contain {hour,key1} and {hour,key2} respectively.

# list of dicts 1 (dict1)
[
 {'hour': '2:00', 'key1': 1},
 {'hour': '3:00', 'key1': 2},
 {'hour': '4:00', 'key1': 3},
 {'hour': '5:00', 'key1': 4},
]

# list of dicts 2 (dict2)
[
 {'hour': '2:00', 'key2': 501},
 {'hour': '3:00', 'key2': 502},
 {'hour': '4:00', 'key2': 503},
 {'hour': '5:00', 'key2': 504},
]

This is what I tried so far but it guess there is another way without loops:

dict1 = []
for row in dict0:
    dictionary = {'hour': row['hour'], 'key1': row['key1']}
    dict1.append(dictionary)

dict2 = []
for row in dict0:
    dictionary = {'hour': row['hour']),'key2': row['key2']}
    dict2.append(dictionary)

Upvotes: 0

Views: 90

Answers (3)

Cristofor
Cristofor

Reputation: 2097

This is the sexyest one:

d = [
 {'hour': '2:00', 'key1': 1, 'key2': 501},
 {'hour': '3:00', 'key1': 2, 'key2': 502},
 {'hour': '4:00', 'key1': 3, 'key2': 503},
 {'hour': '5:00', 'key1': 4, 'key2': 504},
]

[[{"hour": l["hour"], key: l[key]} for l in d if key in  l.keys()] for key in ["key1","key2"]]

Upvotes: 1

Barmar
Barmar

Reputation: 781004

You can do it with two list comprehensions, but otherwise it's essentially the same.

dict1 = [{'hour': row['hour'], 'key1': row['key1']} for row in dict0]
dict2 = [{'hour': row['hour'], 'key2': row['key2']} for row in dict0]

If you want to it with just one list comprehension, you can apply the techniques in Unpacking a list / tuple of pairs into two lists / tuples. The list comprehension creates pairs of dicts, and then these are unpacked into separate result lists.

dict1, dict2 = zip(*[
    ({'hour': row['hour'], 'key1': row['key1']}, {'hour': row['hour'],'key2': row['key2']})
    for row in dict0])

Personally, I don't think this is any clearer.

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117876

A pair of list comprehensions could handle this

>>> [{'hour': d['hour'], 'key1': d['key1']} for d in data]
[{'hour': '2:00', 'key1': 1},
 {'hour': '3:00', 'key1': 2},
 {'hour': '4:00', 'key1': 3},
 {'hour': '5:00', 'key1': 4}]
>>> [{'hour': d['hour'], 'key2': d['key2']} for d in data]
[{'hour': '2:00', 'key2': 501},
 {'hour': '3:00', 'key2': 502},
 {'hour': '4:00', 'key2': 503},
 {'hour': '5:00', 'key2': 504}]

though obviously those both still include loops

Upvotes: 1

Related Questions