社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

比较两本词典的关键字。如果键匹配,则将这些键、值复制到python中的文件中

dubru • 6 年前 • 1721 次点击  

我需要比较两个字典的键,如果键是匹配的,那么将这些键、值复制到文件中。

这里的要求是我有两个文件,我想读取所有不是以 # 把它放在两本字典里。然后比较两个字典的键。

假设我有第一个文件密钥 dict1 和第二个文件密钥 dict2 我想比较一下 命令1 带钥匙 命令2 键如果 命令1 钥匙与 命令2 然后从中复制匹配密钥的值 命令1 命令2 . 不应更改文件中键值的顺序。

下面是我遵循的方法,但它不符合我的要求。

with open(file1) as bl_file:
    content_bld_file = bl_file.readlines()
for i in content_bl_file:
    if '#' not in i:
        bl_d = {}
        bl_var1 = (i.split("="))
        if len(bl_var1)>1:
            bl_d[bl_var1[0]]=bl_var1[1]
        if len(bl_d) == 1:
            for k, v in bld_d.items():
                bl_file_keys = k
                print(bl_file_keys)

with open(file2) as tr_file:
    content_tr_file = tr_file.readlines()
for i in content_tr_file:
    if '#' not in i:
        tr_d = {}
        tr_var2 = (i.split("="))
        if len(tr_var2)>1:
            tr_d[tr_var2[0]]=tr_var2[1]
        if len(tr_d) == 1:
            for k,v in tr_d.items():
                tr_file_keys = k
                print(tr_file_keys)

因此,从上面我可以阅读和储存钥匙在两个字典,但无法比较。任何帮助都将不胜感激

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/44974
文章 [ 2 ]  |  最新文章 6 年前
fafl
Reply   •   1 楼
fafl    7 年前

你需要找到钥匙的交叉点。试试这个:

a = {1: 2, 3: 4, 5: 6}
b = {1: 5, 2: 6, 3: 7}
a_keys = set(a.keys())
b_keys = set(b.keys())
print(a_keys.intersection(b_keys))  // Prints {1, 3}

要查找一组中而不是另一组中的关键点,只需减去它们:

new_keys = a_keys - b_keys
blhsing
Reply   •   2 楼
blhsing    7 年前

你可以更新 dict2 具有 dict1 两个dict键的交集的值:

d1 = {1: 2, 3: 4}
d2 = {3: 5, 4: 3}
d2.update({k: d1[k] for k in d1.keys() & d2.keys()})

d2 会变成:

{3: 4, 4: 3}