繁体   English   中英

在 Python 字典中查找值所属的键

[英]Find the key to which a value belongs in a Python dictionary

我是 Python 的初学者,我的代码似乎有一个简单的问题,但我无法弄清楚。 我有一个包含多个键的字典,每个键都包含一个值列表,我想做以下事情:对于每个键,查找其名称是否在任何其他键中显示为值,如果是,则 append 其内容为那把钥匙也是。

我认为用一个例子来解释更容易。 我有以下内容:

#define the dictionary
Dictionary = {
    "a": ["x", "z"],
    "b": ["y", "w"],
    "c": ["a", "q"],
    "d": ["w", "a"]
    }

#get all the keys from the dictionary
listOfKeys = []
for key in Dictionary.keys():
    listOfKeys.append(key)

#try to append the key values to any matches 
for key, value in Dictionary.items():
    for element in listOfKeys:
        if element in value:
            Dictionary[?].append(Dictionary[element])

显然,在最后一行,而不是“?”,我应该有value所属的键,但我不知道如何得到它。 之后,我希望字典看起来像这样:

    "a": ["x", "z"],
    "b": ["y", "w"],
    "c": ["a", "q", "x", "z"],
    "d": ["w", "a", "x", "z"]

换句话说,键a的内容被添加到键cd中,因为这些键是a作为值出现的键。 理想情况下,我只会 append 值,如果它们还没有在那个键中,但我想我可以自己解决那个部分。 我在网上找到了一个解决方案(不确定我是否可以在这里链接它)但它似乎只有在值是字符串而不是像我的情况下的列表时才有效。

希望我已经清楚地解释了这一点,以便可以理解。

使用extend()到 append 一个列表到另一个列表。 并使用Dictionary[element]获取匹配键的内容。

if element in value:
    value.extend(Dictionary[element])

value所属的键”实际上只是key ,但更进一步, Dictionary[key]value 所以:

value.append(Dictionary[element])

虽然,您还需要将.append()替换为.extend()以获得所需的 output。

#define the dictionary
Dictionary = {
    "a": ["x", "z"],
    "b": ["y", "w"],
    "c": ["a", "q"],
    "d": ["w", "a"]
    }

#get all the keys from the dictionary
listOfKeys = list(Dictionary.keys())

for key, value in Dictionary.items():
    items_to_add = []
    for letter in value:
        if letter in listOfKeys:
            items_to_add.append(letter) # Store off the keys whose value we need to append
    for item in items_to_add:           # Run this in a second loop so that we're not modifying a list we're currently iterating through
        for new_item in Dictionary[item]:
            if new_item not in value:   # Only add each item if it's not already in the target list
                value.append(new_item)

# Test that we've done it right
expected = {
    "a": ["x", "z"],
    "b": ["y", "w"],
    "c": ["a", "q", "x", "z"],
    "d": ["w", "a", "x", "z"]}

# Does not throw an Exception because at this point, Dictionary and expected are identical
assert Dictionary == expected 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM