【发布时间】: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