从列表中将值分配到字典中

时间:2018-03-12 02:26:41

标签: python list dictionary key

我想创建一个字典,它存储单词中50个状态的全名,以及值中的缩写,给出名称和缩写的列表。我期待一本字典如{'Alabama':'AK','Alaska':'AL',...}。我试过了

state_to_abbrev = {}
for word in states:
    for i in range(50):
        state_to_abbrev[word] = states[i]
        state_to_abbrev[word] = abbreviations[i]

state_to_abbrev

我得到{'Alabama':'WY',  '阿拉斯加':'WY',  '亚利桑那':'WY',  '阿肯色州':'WY',  '加州':'WY',  '科罗拉多':'WY',  '康涅狄格':'WY',  '特拉华州':'WY',  '佛罗里达':'WY',  '格鲁吉亚':'WY',  '夏威夷':'WY',.....}

5 个答案:

答案 0 :(得分:2)

您可以尝试:

df.withColumn('weekday', F.udf(lambda day: dayList[day])(df.day)).show()
+---+-------+
|day|weekday|
+---+-------+
|  0|    SUN|
|  3|    WED|
|  5|    FRI|
+---+-------+

更新

正如评论中所建议的那样,你不需要额外的单词循环,你可以尝试:

state_to_abbrev = {}
for word in states:
    for i in range(50):
        state_to_abbrev[states[i]] = abbreviations[i]

state_to_abbrev

然后,使用state_to_abbrev = {} for i in range(50): state_to_abbrev[states[i]] = abbreviations[i] state_to_abbrev ,您可以在上面的循环中分配单行:

dict comprehension

此外,由于您使用的是两个列表,因此您可以尝试使用state_to_abbrev = {states[i]:abbreviations[i] for i in range(50)} ,也可以在documentation中查找示例:

zip

答案 1 :(得分:0)

尝试enumerate

state_to_abbrev = {}
for i, word in enumerate(states):
    state_to_abbrev[word] = abbreviations[i]

state_to_abbrev

答案 2 :(得分:0)

做你想做的事的天真的方法如下:

state_to_abbrev = {}

for i in range(len(states)):
    state_to_abbrev[states[i]] = abbreviations[i]

你有一个嵌套循环,但这不是你想要的,嵌套循环遍历你的两个列表的笛卡尔积,即:

In [46]: for a in ('a','b'):
    ...:     for n in (1, 2):
    ...:         print(a, n)
    ...:
a 1
a 2
b 1
b 2

In [47]:

但实际上,在Python中,您不是使用索引,而是使用zip迭代两个列表"并行":

state_to_abbrev = {}

for st, abbr in zip(states, abbreviations):
    state_to_abbrev[st] = abbr

真的,您应该知道dict构造函数已经采用了可迭代的键值对,所以真正想要的是:

state_to_abbrev = dict(zip(states, abbreviations))

答案 3 :(得分:0)

这是一个单行版本:( Python 3)

state_to_abbrev = dict(zip(states,abbreviations))

print(state_to_abbrev)

打印出来:

{'Alabama': 'AK', 'Alaska': 'AL', ...}

答案 4 :(得分:0)

您可以尝试以下任何一种方法:

states=['Alabama','Arizona']
abbreviations=['AK','AL']

print(dict([i for i in zip(states,abbreviations)]))
print({i[0]:i[1] for i in zip(states,abbreviations)})

输出:

{'Alabama': 'AK', 'Arizona': 'AL'}
{'Alabama': 'AK', 'Arizona': 'AL'}