gpt4 book ai didi

python - 通过 if 语句进行条件字典查找的问题

转载 作者:太空宇宙 更新时间:2023-11-03 16:30:45 24 4
gpt4 key购买 nike

我有一本字典,我正在其中填充值。这些值通过 for 循环提供给字典。

storageDict = {}
listholder = ["word1", "word2", "word2", "word3", "word4", "word5", "word6", "word7"]
values = ["word1", "word2", "word3", "word2", "word5", "word6", "word7", "word8"]
index_tracker = 0

for each_element in listholder:
if index_tracker == 7:
pass
else:
storageDict[str(each_element)] = values[index_tracker]
index_tracker += 1

print(storageDict)

这给了我以下输出:

 {'word5': 'word6', 'word1': 'word1', 'word3': 'word2', 'word4': 'word5', 'word6': 'word7', 'word2': 'word3'}

虽然所有键值组合都是唯一的,但我想避免字典包含与值键组合相同的键值组合的情况。即在上面的字典中我们有以下两个键值组合:

  • 'word3': 'word2'
  • 'word2': 'word3'

因此,我想在将值-键组合和键-值组合提交到字典之前检查它是否已经在字典中。我想出了以下代码,但 PyCharm 给了我一个 KeyError:

storageDict = {}
listholder = ["word1", "word2", "word2", "word3", "word4", "word5", "word6", "word7"]
values = ["word1", "word2", "word3", "word2", "word5", "word6", "word7", "word8"]
index_tracker = 0

for each_element in listholder:
if index_tracker == 7:
pass
else:
if storageDict[each_element] == values[index_tracker] and storageDict[values[index_tracker]] == each_element:
pass
else:
storageDict[each_element] = values[index_tracker]
index_tracker += 1

print(storageDict)

我想要的输出是针对两种情况的输出:

    {'word5': 'word6', 'word1': 'word1', 'word4': 'word5', 'word6': 'word7', 'word2': 'word3'}

或者:

    {'word5': 'word6', 'word1': 'word1', 'word3': 'word2', 'word4': 'word5', 'word6': 'word7'}

这是KeyError:

Traceback (most recent call last):
File "C:/Users/Admin/PycharmProjects/momely/placementarchitect/testbench.py", line 42, in <module>
if storageDict[each_element] == values[index_tracker] and storageDict[values[index_tracker]] == each_element:
KeyError: 'word1'

我相信我明白为什么会发生错误。通过在条件 if 语句中包含我的检查,我请求尚不存在的字典键的键值。

但是人们如何检查键值呢?

我考虑使用元组,但需要在不同的操作中进行字典的快速循环。

最佳答案

这是一种方法。我基本上zip他们,过滤掉我们不需要的条目,然后将过滤后的列表转换为 dict .

listholder = ["word1", "word2", "word2", "word3", "word4", "word5", "word6", "word7"]
values = ["word1", "word2", "word3", "word2", "word5", "word6", "word7", "word8"]
filtered = []
allItems = zip(listholder, values)
for key, value in allItems:
if not ( (key,value) in filtered or (value, key) in filtered):
filtered.append((key,value))
print dict(filtered)

输出:

{'word5': 'word6', 'word4': 'word5', 'word7': 'word8', 'word6': 'word7', 'word1': 'word1', 'word2': 'word3'}

关于python - 通过 if 语句进行条件字典查找的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37618675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com