简体   繁体   中英

checking if list of dictionary has a dictionary containing specified value

I am trying to check if a list of dictionaries contains a key with a specified value if it does contain a dictionary with this value I want to target this dictionary and if it doesn't I want to create the dictionary

here is what my list of dictionaries looks like

my_list = [
   {"name": "home", "content": "home"}, {"name": "contact", "content": "contact"}
]

I want to check if my_list has a dictionary with a key "name" and a value of as an example "events" which does not exist so I would need to add it to my list and if it did I would want to modify the dictionaries key "content"

if {"name": "events"} in my_list:
   list_found = my_list[index_of_the_dictonary]
else:
   my_list.append({
      "name": "events"
      "content": []
   })

You can add else to for loop to solve the problem:

my_list = [
   {"name": "home", "content": "home"},
   {"name": "contact", "content": "contact"}
]

for x in my_list:
    if x.get('name') == 'events':
        print('Dictionary Found')
        break
else:
    my_list.append({'name': 'events', 'content': []})

print(my_list)
# [{'name': 'home', 'content': 'home'}, {'name': 'contact', 'content': 'contact'}, {'name': 'events', 'content': []}]

An else to for loop is executed only when the for loop is executed normally to its completion ie without break .

Try this:

for d in my_list:
    if d.get('name') == 'events':
        list_found = d # d is the dictonary you expected
        break
else:    
    my_list.append({"name":"events", "content": []}) # Create it

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