从字典列表中选择字典并进行一些更新

2024-04-27 01:07:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下列词典。你知道吗

  player = [{"Cate": "EU91", "Points": 256, "good": 1,  },
            {"Cate": "EU93", "Points": 193, "Good": 3,  },
            {"Cate": "FU91", "Points": 216, "Good": 1,  },
            {"Cate": "EU95", "Points": 256, "good": 1,  },
            {"Cate": "EU93", "Points": 193, "Good": 3,  },
            {"Cate": "FU99", "Points": 216, "Good": 1,  }]

在上面的字典中,我想基于等于EU91或FU91的“Cate”值将特定字典存储到某个变量。我试过的是:

if any(d['Cate'] == 'EU91' or d['Cate'] == 'FU91'  for d in player):
     print('U91 category exists') 

在上面的代码中,我只检查EU91或FU91是否存在。我需要将特定字典(其中“Cate”值等于EU91或FU91)存储在某个变量中,并更新所选字典,如下所示:

list = [ {"Cate": "U91", "Points_A": 256, "good": 1 }, {"Cate": "U91","Points_B": 256, "good": 1 } ]

说明:如果EU91和FU91都存在,则将特定字典“Cate”更新为“U91”,然后将EU91的“Points”更新为“Points\u A”,将FU91的“Points”更新为“Points\u B”。你知道吗

我希望结果是:

var = [{"Cate": "U91", "Points_A": 256, "good": 1 },{"Cate": "U91","Points_B": 256, "good": 1}]

我希望你们都理解我的问题。 有什么想法吗?拜托。你知道吗


Tags: if字典anypoints词典goodplayercate
1条回答
网友
1楼 · 发布于 2024-04-27 01:07:39

使用带if条件的simple for循环。你知道吗

例如

player = [{"Cate": "EU91", "Points": 256, "good": 1,  },
            {"Cate": "EU93", "Points": 193, "Good": 3,  },
            {"Cate": "FU91", "Points": 216, "Good": 1,  },
            {"Cate": "EU95", "Points": 256, "good": 1,  },
            {"Cate": "EU93", "Points": 193, "Good": 3,  },
            {"Cate": "FU99", "Points": 216, "Good": 1,  }]
result = []
for x in player:
    if x['Cate'] == 'EU91':
        x['Points_A'] = x.pop('Points')
    elif  x['Cate'] == 'FU91':
        x['Points_B'] = x.pop('Points')

    if "Points_A" in x or "Points_B" in x:
        x['Cate'] = "U91"
        result.append(x)

print(result)

O/p:

[{'Cate': 'U91', 'good': 1, 'Points_A': 256}, {'Cate': 'U91', 'Good': 1,
 'Points_B': 216}]

相关问题 更多 >