'Finding dictionaries which don't have forbidden key-value pairs
I have the following two lists:
List1 =
[
{"color":"red",
"size":"large"},
{"color":"blue",
"size":"medium"}
]
List2 =
[
{"color":"red",
"size":"large"},
{"color":"blue",
"size":"medium"},
{"color":"yellow",
"size":"small"}
]
What I need is a third list which only contains the difference between List1 and List2, comparing only the "color" keys instead of the whole dictionary. For example, given the above two lists, I'd expect something like:
List3 =
[
{"color":"yellow",
"size":"small"}
]
I have a function that returns a list of dictionaries. These dictionaries contain information on devices currently connected to a network.
I need a list of devices that have connected to the network since the last time checked, using the MAC address of the devices.
The reason I can't compare the whole dicts is because they have a variable inside them that ALWAYS changes.
Solution 1:[1]
I would use pandas module:
import pandas as pd
List1 =[{"color":"red","size":"large"},
{"color":"blue","size":"medium"},
{"color":"black","size":"medium"}]
List2 =[{"color":"red","size":"small"},
{"color":"blue","size":"medium"},
{"color":"yellow","size":"small"}]
List3 = pd.DataFrame(List1+List2).drop_duplicates('color', False).to_dict('records')
'''
[{'color': 'black', 'size': 'medium'}, {'color': 'yellow', 'size': 'small'}]
Solution 2:[2]
For the data you presented, you could create a set of keys to compare in each list and compare the resulting sets with symmetric_difference.
compare = 'color'
colors1 = {d.get(compare) for d in List1}
colors2 = {d.get(compare) for d in List2}
# {'yellow'}
difference = colors1.symmetric_difference(colors2)
# [{'color': 'yellow', 'size': 'small'}]
result = [d for d in List1 + List2 if d.get(compare) in difference]
Solution 3:[3]
You can get a set of colors to avoid in the result using functools.reduce(), and then use a list comprehension to retain only the keys that do not have a color in that set:
colors_to_avoid = reduce(lambda x, y: x | {y["color"]}, List1, set())
result = [item for item in List2 if item["color"] not in colors_to_avoid]
print(result)
This outputs:
[{'color': 'yellow', 'size': 'small'}]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SergFSM |
| Solution 2 | |
| Solution 3 | BrokenBenchmark |
