简体   繁体   English

在python中,结合2个字典的值

[英]In python, combine the values of 2 dictionaries

I'm new to Python, and I have two questions regarding dictionary in python. 我是Python的新手,我有两个关于python字典的问题。

  1. I have dict1 (where the values is already a list ), then I have dict2 with the same keys as dict1 , I want to add the new value to the list of values in dict1 . 我有dict1 (其中值已经是一个list ),那么我已经dict2具有相同keysdict1 ,我希望将新值添加到list中的值dict1 How can I write it? 我该怎么写? Can you show it with an example? 可以举一个例子吗?

     dict1 = {'uid': ['u1'], 'sid': ['s1'], 'os': ['os1']} dict2 = {'uid': ['u2'], 'sid': ['s2'], 'os': ['os2']} 

    Expected output: 预期产量:

     dict1 = {'uid': ['u1', 'u2'], 'sid': ['s1', 's2'], 'os': ['os1', 'os2']} 

  1. I will be process a lot of lines in a text file, with each line creating a new dictionary. 我将在一个文本文件中处理很多行,每行创建一个新字典。 Here is the idea of my code: 这是我的代码的想法:

     count = 0 for line in f: if count == 0: dict1 = parse_qs(line) count = count+1 else: dict2 = parse_qs(line) #combine dict1 with dict 2, and assign the new dict to dict1 

Is there a better way that uses less memory or runs faster (still using dictionary)? 是否有更好的方法使用更少的内存或运行得更快(仍然使用字典)?

Thank you in advance for your help! 预先感谢您的帮助!

Since you're apparently not allowed to rewrite you parser, you can do: 由于显然不允许您重写解析器,因此可以执行以下操作:

for k in dict1:
    dict1[k].extend(dict2.get(k, []))

You can drop the .get and use direct subscription if the keys from both dicts are always matching. 如果两个字典的键始终匹配,则可以删除.get并使用直接订阅。

for k in dict1:
    dict1[k].extend(dict2[k])

Otherwise, you can create one defaultdict(list) and let your parser append values to that. 否则,您可以创建一个defaultdict(list)并让解析器将值附加到该值。

You can do like this, 你可以这样

for key in dict1.keys():
     if dict2.has_key(key):
         dict1[key].extend(dict2[key])

if you are using python3 you can use key in dict2 instead of dict2.has_key(key) . 如果您使用的是python3 ,则可以key in dict2使用key in dict2而不是dict2.has_key(key)

Result 结果

{'os': ['os1', 'os2'], 'sid': ['s1', 's2'], 'uid': ['u1', 'u2']}

If you don't want the two dictionaries anymore then you can do this: 如果您不再需要这两个字典,则可以执行以下操作:

def merge_dict(dict1, dict2):
    for k in dict1:
        try:
            dict1[k].extend(dict2[k])
        except KeyError:
            pass
    return dict1

Else if you want to preserve them both for future use, try this 否则,如果您想同时保存它们以备将来使用,请尝试此操作

def merge_dict(dict1, dict2):
    new_dict = {}
    keys = dict1.keys() + dict2.keys()
    for k in keys:
        try:
            new_dict[k] = dict1[k]
        except KeyError:
            new_dict[k] = dict2[k]
            continue
        try:
            new_dict[k]+= dict2[k]
        except KeyError:
            pass
    return dict1

this may be helpful to you. 这可能对您有帮助。

from itertools import chain
from collections import defaultdict

# ------ for dict1 -------#

u1 = [1,2,3]
s1 = ['a','b','c']
x1 = [10,100,1000]

# ------ for dict2 -------#

u2 = [4,5,6]
s2 = ['d','e','f']
x2 = ['aa','bb','cc']

dict1 = {1:u1,2:s1,3:x1}
dict2 = {1:u2,2:s2,3:x2}

dict3 = defaultdict(list)
for a, b in chain(dict1.items(), dict2.items()):
     dict3[a].append(b)

#for a, b in dict3.items():
#    print(a, b)

print dict3

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

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