如果我使用not in,它仍然会追加新的密钥对值,即使列表中已经有一个特定的值。
dict1 = {'a': 0, 'a': 5, 'b': 1, 'c': 2}
list1 = [{'a': 0}] # This key-pair value is already in the list1 but
# still added from dict1.
new1 = []
new2 = []
for key, value in dict1.items():
if value not in list1:
new1.append(key)
new2.append(value)
new0 = {new1[i]: new2[i] for i in range(len(new1))}
list1.append(new0)期望的产出是:
list1 = [{'a': 0, 'a': 5, 'b': 1, 'c': 2}](因为我不想覆盖键/s)
发布于 2022-04-21 08:21:42
由于您没有提供示例数据,我必须在这里进行一些猜测。如果我猜错了,请提供所需的信息。
你在list1上打电话给list1。列表没有items函数。相反,我怀疑您的list1实际上是一本字典,例如:
list1 = {
"a":1,
"b":2,
"c":3
}在当前循环中,检查该值是否在list2中。如果list2实际上是一个列表,那么这样做是正确的。但是,根据您的标题,我假设您实际上要做的是检查键是否在list2中,如果没有,则将键:value添加到list2中。您不能向列表中添加键:值对,所以我假设list2也应该是一个字典。您可以将它们添加为元组,但根据标题,我假设这不是您想要的。
如果您实际上想将它作为键:值对添加到字典中,您可以这样做:
list2 = {}
for key, value in list1.items():
if key not in list2.keys(): # check if this key already exists
list2[key] = value # if not, add they key with the value由于list1和list2实际上不是list的实例,而是dict的实例,所以我建议重新命名变量以避免将来的混淆。希望这能帮上忙!
在问题更新后的编辑
示例数据有一个小错误,因为有两个a键,这意味着第一个{'a':0}已经在dict1中被覆盖了。
dict1 = {'a': 0, 'b': 5, 'c': 1, 'd': 2}
list1 = [{'a': 0}] 据我所知,您希望检查该值是否已包含在字典列表中。因此,我们需要从这些字典中获取所有的值。
因为您不想覆盖任何键,所以它需要是一个字典列表,每个字典只有一个键。因此,我们可以得到每一本字典,得到钥匙。这将返回一个dict_keys对象,我们可以将其转换为一个列表。由于list1中的每个字典总是只有一个键,所以我们只需从上述的lsit中获取第一个键即可。
[list(x.values())[0] for x in list1]把它放在循环中我们得到
for key, value in dict1.items():
if not value in [list(x.values())[0] for x in list1]:
# If no dictionary exists within `list1` with this value
list1.append({key:value}) # then add it as a new dictionary这会回来的
[{'a': 0}, {'b': 5}, {'c': 1}, {'d': 2}]您可以使用不同的dict1再次运行此代码,并且它不会覆盖list1中的键,例如:
dict1 = {'a': 9}输出会变成
[{'a': 0}, {'b': 5}, {'c': 1}, {'d': 2}, {'a': 9}]https://stackoverflow.com/questions/71950970
复制相似问题