【问题标题】:Concatenating two dictionaries with same keys?用相同的键连接两个字典?
【发布时间】:2019-09-05 00:24:29
【问题描述】:

编辑:TL;DR

我有什么:

dict_1 = {'file1': {'word1': 5, 'word2: 3'}, 'file2': {'word1': 12, 'word2: 0'}}


dict_2 = {'file1': {'total_words': 11}, 'file2': {'total_words': 18}}

我想要什么

concat_dict = {'file1': {'word1': 5, 'word2: 3', 'total_words' : 11}, 'file2': {'word1': 12, 'word2: 0', 'total_words' : 18}} 

dict_2 中的关联值添加到dict_1 中的公共键中。 我有一本由文本文件名和这些文件中特定单词的字数组成的字典。

原帖

除了每个文件中的特定单词之外,我还想添加每个文件中的总单词数(每个键的值),我该怎么做?

我的代码:

# dict_one = previously defined
# filter_words = previously defined
out={}
for k, v in dict_one.items():
    #create empty list
    new = []
    #for each filter word
    for i in filter_words:
        new.extend(re.findall(r"{}".format(i),v) )

    out[k] = dict(Counter(new))

# count total number of words
total_dict = {k: len(v) for k,v in dict_one.items()}

基本上,我想连接 total_dict{} 和 out{} 字典,因为它们具有相同的键,但我不确定如何。

另外:我有一段时间没看这段代码了,但我忘记了这个表达式的作用:

new.extend(re.findall(r"{}".format(i),v) )

我知道它正在扩展列表,但我对 re.findall 的论点感到困惑:

r"{}".format(i),v)

这是什么意思/做什么?

【问题讨论】:

  • 在这个特定的例子中,"{}".format(i) 类似于str(i)r 是不必要的。见Format String Syntax

标签: python python-3.x dictionary concatenation


【解决方案1】:

您可以使用字典理解和this answer 中描述的方法来合并内部字典:

dict_1 = {'file1': {'word1': 5, 'word2': '3'}, 'file2': {'word1': 12, 'word2': '0'}}
dict_2 = {'file1': {'total_words': 11}, 'file2': {'total_words': 18}}

concat_dict = {k:{**dict_1[k], **dict_2[k]} for k in dict_1}
concat_dict

输出:

{'file1': {'word1': 5, 'word2': '3', 'total_words': 11},
 'file2': {'word1': 12, 'word2': '0', 'total_words': 18}}

【讨论】:

  • 我遇到了一个奇怪的错误,我似乎在网上找不到:TypeError: 'int' object is not a mapping
  • 您的示例有几个拼写错误,我必须更正。例如,这个字符串'word2: 3' 应该是'word2': '3'。尝试修复这些问题或复制粘贴我的代码以检查它是否运行。
  • 复制和粘贴代码确实有效。但是当我使用我的实际字典时,它似乎不起作用。例如,我有:dict_1 = {'file1': {'word1': 2}} dict_2 = {'file1': 190952} concat = {} concat = {k:{**dict_1[k], **dict_2[k]} for k in dict_1} 返回错误 'int' object is not a mapping。我从控制台将这些键/值对复制并粘贴到我的 dict_1 和 dict_2 创建中。
  • 对不起!我刚刚想通了。我的第二个字典没有与原始字典格式相同的正确键值对。
  • 您可以将dict_2 创建为dict_2 = {k: {'total_words':len(v)} for k,v in dict_one.items()}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多