Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
向字典中的所有键添加字符串(Python)_Python_String_Dictionary - Fatal编程技术网

向字典中的所有键添加字符串(Python)

向字典中的所有键添加字符串(Python),python,string,dictionary,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.c

我刚接触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文件用于相同的过程。我想在dictionary中的key中添加一个字符串,比如
“@d1”
,这样我就可以指出key来自文档1

如何向字典中的所有键添加
“@1”

基本上,我的字典的形式如下:

{'word1': 1, 'word2': 1, 'word3': 2, ....}
我希望它是:

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

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

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

您可以使用
dict
构造函数重新生成dict,将文件号附加到每个键的末尾:

>>> d = {'a': 1, 'b': 2}
>>> file_number = 1
>>> dict(("{}@{}".format(k,file_number),v) for k,v in d.items())
>>> {'a@1': 1, 'b@1': 2}

我有一个目录,如下所示

转换后的json如下所示

>>> d = {'a': 1, 'b': 2}
>>> file_number = 1
>>> dict(("{}@{}".format(k,file_number),v) for k,v in d.items())
>>> {'a@1': 1, 'b@1': 2}
def prefix_key_dict(prefix,test_dict):
   res = {prefix + str(key).lower(): val for key, val in test_dict.items()}
   return res

temp_prefix = 'column_'
transformed_dict = [prefix_dict(temp_prefix,each) for each in table_col_list]