I'm new to Python.
I'm trying to compare a dictionary results against a list of dictionaries d . If it's equal to a dictionary in the list d (apart from lacking in results 'name' key), I should print one of the values (name), if not equal to any - print no match.
In particular: d - list of dictionaries:
[OrderedDict([('name', 'Alice'), ('AAA', '2'), ('BBB', '8'), ('CCC', '3')]), OrderedDict([('name', 'Bob'), ('AAA', '4'), ('BBB', '1'), ('CCC', '5')]),
OrderedDict([('name', 'Charlie'), ('AAA', '3'), ('BBB', '2'), ('CCC', '5')])]
results - dictionary:
{'AAA': 4, 'BBB': 1, 'CCC': 5}
Since results is identical to the similar part of the dict list d , I should return 'name' in that d dict list (Bob in this case)
I was trying the following code, but it doesn't seem to work:
for i in range(len(d)):
if key in d[i] != 'name':
for k, v in results.items and d[i].items():
if results.items() == d[i].items():
print(d[i]['name'])
else:
print("No match")
I'd be happy if you could provide some simple and more detailed explanations, as I'm not advanced yet:)
Thanks!
Here's a one-liner:
next((x["name"] for x in d
if results == {k: int(v) for k, v in x.items() if k != 'name'}),
"No match")
# Output: 'Bob'
Alright, so that's not super helpful. Let's debug your code.
for k, v in results.items and d[i].items():
if results.items() == d[i].items():
The problem in your code is that you are comparing a list of key-value pair as a sequence . There's no guarantee that the regular dict (non-OrderedDict) will give you the .items()
in the same order as the OrderedDict. Instead you could just say (with a little bit of dict-comprehension:
if {k: int(v) for k, v in d[i].items() if k != 'name'} == result:
print(d[i]["name"])
PS: Please use the slightly better: for item in items: something(item)
instead of for i in range(len(items)): something(items[i])
construct. Put this together with a little bit list/dict comprehension you'll get the answer in the first line. :)
Easy to understand:
done = False
for di in d:
l = list(di.values())
l.pop(0)
l = [int(i) for i in l]
if l == list(results.values()):
print(di['name'])
done = True
if done == False:
print('no match found')
Output for your results dictionary:
Bob
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.