python - 将字符串添加到字典中的所有键(Python)

标签 python string dictionary

我是Python和Pyspark的新手,正在练习TF-IDF。
我将txt文件中句子中的所有单词分开,删除了标点符号,删除了停用词列表中的单词,并将它们保存为带有以下代码的字典。

x = text_file.flatmap(lambda line: str_clean(line).split()    
x = x.filter(lambda word: word not in stopwords    
x = x.reduceByKey(lambda a,b: a+b)    
x = x.collectAsMap()


我有10个不同的txt文件用于同一过程。我想在字典的键中添加一个像"@d1"这样的字符串,以便我可以指示该键来自文档1。

如何将"@1"添加到词典中的所有键?

本质上,我的字典采用以下形式:

{'word1': 1, 'word2': 1, 'word3': 2, ....}


我希望它是:

{'word1@d1': 1, 'word2@d1': 1, 'word3@d1': 2, ...}

最佳答案

尝试dictionary comprehension

{k+'@d1': v for k, v in d.items()}


在Python 3.6+中,可以使用f字符串:

{f'{k}@d1': v for k, v in d.items()}

关于python - 将字符串添加到字典中的所有键(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48681634/

相关文章:

python - 如何迭代字典的所有可能值?

python - python manager dict 会自动锁定它的值吗?

python - Shapely : "shapely.geos.TopologicalError: The operation ' GEOSIntersection_r' produced a null geometry"中的多边形相交错误

python - 使用Python将JSON转换为CSV

c++ - 如何在字符串中添加换行符?

swift - 如何从 Swift 中的 ASCII 码中获取字符串?

JSON数据: A_Geo: "MULTIPOINT ((121.5831587 24.9971109))" need to be parsed into dictionary

python - 合并两个字典并保留第一个字典的值

python - 如何在 Python 中获取两个 html 标签之间的所有内容?

c - 替换字符串的单个字符元素 C