[英]Iterating through a dictionary and assigning values to a variable
I have a dictionary "d" which has a 10 keys with pyspark dataframes as values.我有一个字典“d”,它有一个 10 个键,以 pyspark 个数据帧作为值。
>> d.keys()
dict_keys (['Py1', 'Py2', 'Py3', 'Py4', 'Py7', 'Py8', 'Py15', 'Py20', 'Py21', 'Py22']
I am currently taking each key and its value, then assigning it to a variable like so:我目前正在获取每个键及其值,然后将其分配给一个变量,如下所示:
df1 = d['Py1']
df2 = d['Py2']
df3 = d['Py3']
.
.
.
df10 = d['Py22']
I then do various manipulations using pyspark. What is the best way achieving this without the redundancy?然后我使用 pyspark 进行各种操作。在没有冗余的情况下实现此目的的最佳方法是什么? here is what i attempted..
这是我尝试的..
newname = "df"
counter = 1
for key in df_list.keys():
key = newname + str(counter)
counter+=1
print (key)
But when i do print(df1) i get a "name 'df1' is not defined" error.但是当我执行 print(df1) 时,出现“名称‘df1’未定义”错误。
Let's assume you have your df
in a list called dfs
.假设您的
df
位于名为dfs
的列表中。 I would use a combination of a comprehension and the enumerate
function.我会结合使用理解和
enumerate
function。
out = {newname + str(i): df for i, df in enumerate(dfs, 1)}
The function enumerate
wraps an iterable and returns the tuple (index, value)
. function
enumerate
包装了一个可迭代对象并返回元组(index, value)
。 It is very convenient when you need to refer to both the value and location of each element in a list.当您需要引用列表中每个元素的值和位置时,它非常方便。 Also note the use of tuple unpacking to give a name to both of the items returned by
enumerate
.另请注意使用元组拆包为
enumerate
返回的两个项目命名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.