简体   繁体   中英

Remove key and value pairs when the value of those pairs are less than value of another pairs in a dictionary of dictionaries

I want to remove pairs of key and value when those pairs have the value smaller than another pairs in a dictionary of dictionaries. Suppose that I have a dictionary of dictionaries as below:

ex_dict = {'C1': {'I1': 1, 'I2': 1.5, 'I3': 2}, 'C2': {'I2': 2, 'I3': 3, 'I4': 3.5}, 'C3': {'I4': 2, 'I5': 4, 'I6': 3}, 'C4': {'I1': 2, 'I3': 3.5, 'I6': 5}, 'C5': {'I7': 1, 'I8': 1.5, 'I9': 2}}

I want the expected output as follow:

new_ex_dict = {'C1': {}, 'C2': {'I2': 2, 'I4': 3.5}, 'C3': {'I5': 4}, 'C4': {'I1': 2, 'I3': 3.5, 'I6': 5}, 'C5': {'I7': 1, 'I8': 1.5, 'I9': 2}}

How can I do this efficiently? Any help will be much appreciated.

This is my quick solution

ex_dict = {'C1': {'I1': 1, 'I2': 1.5, 'I3': 2}, 'C2': {'I2': 2, 'I3': 3, 'I4': 3.5}, 'C3': {'I4': 2, 'I5': 4, 'I6': 3}, 'C4': {'I1': 2, 'I3': 3.5, 'I6': 5}, 'C5': {'I7': 1, 'I8': 1.5, 'I9': 2}}
temp_dict = {}
new_ex_dict = {}

for main_key in ex_dict:
    for k, v in ex_dict[main_key].items():
        temp_dict.setdefault(k, []).append((main_key, v))

for k, v in temp_dict.items():
    max_value = max(v, key=lambda x: x[1])
    main_key = max_value[0]
    new_ex_dict.setdefault(main_key, {})[k] = max_value[1]

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