简体   繁体   English

Python - 根据前者的键值将字典的键附加为另一个键中的键值

[英]Python - Append keys of a dictionary as key values in another based on the key values of the former

I have a dictionary that is one where each key is associated to a list. 我有一个字典,其中每个键与列表相关联。 For example: 例如:

a = ['apple', 'pear', 'banana']
b = ['car', 'plane', 'boat']
c = ['cat', 'dog', 'bird']
d = {'a' : a, 'b' : b, 'c' : c}

And I have a list of dictionaries where a particular key value in each dictionary will be a string that matches one of the strings from the lists. 我有一个字典列表,其中每个字典中的特定键值将是一个字符串,匹配列表中的一个字符串。 Such as: 如:

x = [{'thing' : 'apple'}, {'thing': 'dog'}, {'thing' : 'boat'}]

What I want to do is add a key to each dictionary where the value matches the name of the list where the string is found. 我想要做的是为每个字典添加一个键,其中值与找到字符串的列表的名称相匹配。 Resulting in: 导致:

x = [{'thing' : 'apple', 'list' : 'a'}, {'thing' : 'dog', 'list' : 'c']}, {'thing': 'boat', 'list': 'b'}]

I have tried 我努力了

for k in d:
    for m in x:
        if m['thing'] in k:
            m['list'] = k

I have a feeling that I'm overcomplicating this but haven't been able to figure out where I'm going wrong. 我有一种感觉,我过于复杂,但却无法弄清楚我哪里出错了。 Any advice is appreciated. 任何建议表示赞赏。

Edit: Something I forgot to mention in my post when translating it to more general terms is the that the strings which are in a,b, and c are substrings of those found in x. 编辑:我在文章中将其翻译成更一般的术语时忘记提及的是a,b和c中的字符串是x中找到的字符串。 So x would actually be more like x = [{'thing' : 'apple | 所以x实际上更像是x = [{'thing':'apple | fruit'}, {'thing': 'dog | fruit'},{'thing':'dog | animal'}, {'thing' : 'boat | 动物'},{'东西':'船| vehicle'}] 车辆'}]

Check this code 检查此代码

a = ['apple', 'pear', 'banana']
b = ['car', 'plane', 'boat']
c = ['cat', 'dog', 'bird']
d = {'a' : a, 'b' : b, 'c' : c}

x = [{'thing' : 'apple'}, {'thing': 'dog'}, {'thing' : 'boat'}]

# with  list comprehension
nx = [{'thing' : m['thing'], 'list' : key} for key, listVals in d.items() for m in x if m['thing'] in listVals]

# normal way.
# nx = []
# for m in x:
#     for key, listVals in d.items():
#         if m['thing'] in listVals :
#             nx.append({'thing' : m['thing'], 'list' : key})

print(nx)

One option is to create an inverse of d where the keys are the values in each of the lists and the values are the keys in d . 一种选择是创建d的倒数,其中键是每个列表中的值,值是d中的键。 Then use this inverse dictionary to update x . 然后使用此反向字典更新x

First create the inverse dict: 首先创建反向字典:

d_inv = {d[k][i]: k for k in d for i in range(len(d[k]))}
print(d_inv)
#{'apple': 'a', 'banana': 'a', 'car': 'b', 'pear': 'a', 'dog': 'c', 'cat': 'c', 
# 'plane': 'b', 'bird': 'c', 'boat': 'b'}

This assumes that you do not have the same element appearing in more than one list. 这假设您没有出现在多个列表中的相同元素。

Now update x : 现在更新x

for elem in x:
    elem['list'] = d_inv[elem['thing']]
print(x)
[
    {'thing': 'apple', 'list': 'a'},
    {'thing': 'dog', 'list': 'c'},
    {'thing': 'boat', 'list': 'b'}
]

I appreciate the above comment(s) for this problem. 我很欣赏上述关于这个问题的评论。

As we are searching for a key inside list and a , b , c are keys of dictionary that refers/points to list. 当我们搜索内部键列表时, abc是引用/指向列表的字典键。 k in if m['thing'] in k refers key not the list so it should be changed to d[k] . k in if m['thing'] in k k中的if m['thing'] in k是指密钥而不是列表,那么它应该改为d [k]

http://rextester.com/JVRG57284 http://rextester.com/JVRG57284

Have a look at your modified code below (please comment if you're not satisfied with the code or if it doesn't satisfy your need or if it fail for any of your test cases): 请查看下面的修改后的代码(如果您对代码不满意或者如果它不能满足您的需求或者您的任何测试用例失败,请发表评论):

import json

a = ['apple', 'pear', 'banana']
b = ['car', 'plane', 'boat']
c = ['cat', 'dog', 'bird']
d = {'a' : a, 'b' : b, 'c' : c}

x = [{'thing' : 'apple'}, {'thing': 'dog'}, {'thing' : 'boat'}]

for k in d:
    for m in x:
        if m['thing'] in d[k]:
            m['list'] = k

# pretty printing x dictionary
print(json.dumps(x, indent=4))

"""
[
    {
        "list": "a",
        "thing": "apple"
    },
    {
        "list": "c",
        "thing": "dog"
    },
    {
        "list": "b",
        "thing": "boat"
    }
]
"""

You can use a list comprehension and dictionary unpacking: 您可以使用列表解析和字典解包:

a = ['apple', 'pear', 'banana']
b = ['car', 'plane', 'boat']
c = ['cat', 'dog', 'bird']
d = {'a' : a, 'b' : b, 'c' : c}
x = [{'thing' : 'apple'}, {'thing': 'dog'}, {'thing' : 'boat'}]
final_results = [{**i, **{'list':[a for a, b in d.items() if i['thing'] in b][0]}} for i in x]

Output: 输出:

 [{'list': 'a', 'thing': 'apple'}, {'list': 'c', 'thing': 'dog'}, {'list': 'b', 'thing': 'boat'}]

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

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