【发布时间】:2020-11-05 19:52:14
【问题描述】:
我想补充一下:
{
"Category": "Fruit"
}
到这里:
{
"Category": "Vegetable"
{
所以我可以拥有:
"Name": "Menu1",
"Categories":[
{
"Category": "Fruit"
{
}
"Category": "Vegetable"
{
]
我正在创建一个字典列表,有时我可以有 2 个具有相同键 ["Name"] 的字典,我想避免将两个具有相同名称的字典分开。目前我这样做是为了检查“名称”是否已经存在,如果不存在,则创建它并将其添加到列表中:
if len(List) != 0: #checking if the list has something
for x in List:
if menu['Name'] == x['Name']:
menu['Category'].append(Category) #if exist add data to the existing one
break
else:
List.append(menu) #if doesn't exist add it
break
else:
List.append(menu) #if is empty add an item
【问题讨论】:
-
在 Python 中空列表是错误的,你
if List:相当于if len(List) != 0: -
['Category']应该是menu['Category'] -
如果你在
if和else中都break,你只处理List的第一个元素,所以没有理由循环。 -
也许第一个
else:应该不缩进,所以它在for循环上,而不是if。 -
给出输入和期望输出的例子
标签: python arrays json dictionary