简体   繁体   中英

From dict with tuples to dict with lists

I have a dictionary in Python containing time stamps, t, and value stamps, v, looking like this:

dict_example = {key1: [(t1, v1), (t2, v2), (t3, v3)],
                key2: [(t4, v4), (t5, v5), (t6, v6)],
                ...}

What I want to do is to make two separate dicts looking like this:

dict_example_timestamps = {key1: [t1, t2, t3],
                           key2: [t4, t5, t6],
                           ...}

dict_example_valuestamps = {key1: [v1, v2, v3],
                            key2: [v4, v5, v6],
                            ...}

That is, two separate dicts with one containing a list of timestamps per key and the other one containing a list of valuestamps per key.

I have 'succeeded' in getting all eg timestamps as a list but they need to be 'grouped' per key.

You can try this:

dict_example = {"key1": [(21, 45), (23, 30), (23, 23)],
            "key2": [(10, 45), (15, 51), (56, 6)]}
dict_example_timestamps = {a:[c for c, d in b] for a, b in dict_example.items()}
dict_example_valuestamps = {a:[d for c, d in b] for a, b in dict_example.items()}
print(dict_example_timestamps)
print(dict_example_valuestamps)

Output:

{'key1': [21, 23, 23], 'key2': [10, 15, 56]}
{'key1': [45, 30, 23], 'key2': [45, 51, 6]}

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