簡體   English   中英

檢查字典列表是否具有包含指定值的字典

[英]checking if list of dictionary has a dictionary containing specified value

我正在嘗試檢查字典列表是否包含具有指定值的鍵,如果它確實包含具有該值的字典,我想以此字典為目標,如果不是,我想創建字典

這是我的字典清單

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

我想檢查my_list是否有一個字典,該字典具有鍵"name"和值"name"作為示例"events" ,該字典不存在,因此我需要將其添加到列表中,如果確實存在,我想修改字典關鍵的"content"

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

您可以將else添加到for循環中以解決問題:

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': []}]

一個elsefor ,只有當循環執行for循環正常執行其完成即沒有break

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM