比较两个字典并更改第二个字典中的键(如果键作为第一个字典中的子值存在)

发布于 2025-01-10 23:59:19 字数 328 浏览 0 评论 0原文

如果 d2 的键与 d1id 的值匹配,则需要帮助重新映射 d2 的键。如果存在不匹配的密钥,请将其丢弃。

d1={'A':{'id':'a'},'B':{'id':'b'}}
d2={'a':1,'b':2, 'c':3}

预期输出:

{'A': 1, 'B': 2}

Need help remapping the keys for d2 if they match the value for id in d1. In case there are keys that are unmatched, drop them.

d1={'A':{'id':'a'},'B':{'id':'b'}}
d2={'a':1,'b':2, 'c':3}

Expected output:

{'A': 1, 'B': 2}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

尘曦 2025-01-17 23:59:19

您可以遍历d1并使用d2作为查找来修改值:

for k, d in d1.items():
    d1[k] = d2.get(d['id'])

如果您想修改df2,您可以使用字典理解:

d2 = {k: d2.get(d['id']) for k, d in d1.items()}

或使用两个循环(一次修改 df1 中存在的键的值,一次删除 df1 中不存在的任何键):

for k, d in d1.items():
    d2[k] = d2.pop(d['id'])
for k in list(d2.keys() - d1.keys()):
    d2.pop(k)

输出:

{'A': 123, 'B': 123}

You could traverse d1 and use d2 as a lookup to modify values:

for k, d in d1.items():
    d1[k] = d2.get(d['id'])

If you want to modify df2 instead, you could use a dict comprehension:

d2 = {k: d2.get(d['id']) for k, d in d1.items()}

or use two loops (once to modify values of keys that exist in df1 and once to remove any keys that don't exist in df1):

for k, d in d1.items():
    d2[k] = d2.pop(d['id'])
for k in list(d2.keys() - d1.keys()):
    d2.pop(k)

Output:

{'A': 123, 'B': 123}
柠檬色的秋千 2025-01-17 23:59:19

这可能就是您想要的

d1={'A':{'id':'a'},'B':{'id':'b'}}
d2={'a':123,'b':123}

for key, id_map in d1.copy().items():  # view over soft copy won't mutate
    try:
        d1[key] = d2[id_map["id"]]
    except KeyError:
        pass
>>> d1
{'A': 123, 'B': 123}

但是,未映射的值将保持不变(即,如果有 C,但其映射中没有 id,或者没有 c in d2..)

>>> d1={'A':{'id':'a'},'B':{'id':'b'},'C':{'id':'c'}}
[..]
>>> d1
{'A': 123, 'B': 123, 'C': {'id': 'c'}}

如果您想丢弃未映射的值,您可以在 except 中使用 del d1[key] 执行此操作,或者简单地创建一个新值字典将键和值打包到(如果引发 KeyError)
或者,如果这是一个错误(即 C 必须 存在),您可以简单地让 KeyError 向调用者引发并让它处理后果

This is probably what you're after

d1={'A':{'id':'a'},'B':{'id':'b'}}
d2={'a':123,'b':123}

for key, id_map in d1.copy().items():  # view over soft copy won't mutate
    try:
        d1[key] = d2[id_map["id"]]
    except KeyError:
        pass
>>> d1
{'A': 123, 'B': 123}

However, unmapped values will remain the same (ie if there is C, but no id in its mapping, or no c in d2..)

>>> d1={'A':{'id':'a'},'B':{'id':'b'},'C':{'id':'c'}}
[..]
>>> d1
{'A': 123, 'B': 123, 'C': {'id': 'c'}}

If you want to discard unmapped values, you could do so here with del d1[key] in the except or simply create a new dict to pack the keys and values into (never added if KeyError is raised)
Alternatively, if this is an error (ie. C must exist), you can simply let KeyError raise to the caller and have it deal with the consequences

時窥 2025-01-17 23:59:19

只要每个 'val' 在 d1 的子词典中最多出现一次(即 d1 中的 key: {'id': val} 对),就可以迭代在 d1 的项目上,如下所示:

d1 = {'A': {'id': 'a'}, 'B': {'id': 'b'}, 'C': {'id': 'c'}}
d2 = {'a': 123, 'b': 12, 'd': 8}

d3 = {k: d2[v['id']] for k, v in d1.items() if v['id'] in d2}
print(d3)
>>> {'A': 123, 'B': 12}

由于您需要检查 d1 中的所有键值对,因此从时间和空间效率角度来看,这是您能做的最好的事情。

但是,如果您要使用相同的 d1 来“重新键入”许多 d2 字典,则构建反向索引以供重用可能会更快:

reverse_mapping = {v['id']: k for k, v in d1.items()}
def rekey(dict_to_rekey, reverse_map):
    return {reverse_map[k]: dict_to_rekey[k] 
            for k in dict_to_rekey.keys() & reverse_map.keys()}

d3 = rekey(d2, reverse_mapping)

As long as each 'val' appears at most once in d1's subdictionaries (i.e. the key: {'id': val} pairs in d1), you can iterate over d1's items like so:

d1 = {'A': {'id': 'a'}, 'B': {'id': 'b'}, 'C': {'id': 'c'}}
d2 = {'a': 123, 'b': 12, 'd': 8}

d3 = {k: d2[v['id']] for k, v in d1.items() if v['id'] in d2}
print(d3)
>>> {'A': 123, 'B': 12}

Since you need to check all key-value pairs in d1, this is the best you can do in terms of time and space efficiency.

However, if you will be 're-keying' many d2 dictionaries with the same d1, it may be faster to build a reverse-index to reuse:

reverse_mapping = {v['id']: k for k, v in d1.items()}
def rekey(dict_to_rekey, reverse_map):
    return {reverse_map[k]: dict_to_rekey[k] 
            for k in dict_to_rekey.keys() & reverse_map.keys()}

d3 = rekey(d2, reverse_mapping)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文