迭代列表时出错

时间:2018-03-09 05:11:45

标签: python arrays dictionary append

[{'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}]

这是我的命令。

我的代码,用于列出dict_month的值列表

dict_month = []    
jan_month= []
for x in file_st:
    a=calendar.month_name[int(x['Start Time'][5:7])] #month name
    b=parser.parse(x['Start Time']).strftime("%a")  # day name
    dict_month.append({a:b})     # [{}]

for x in dict_month:
    jan_month.append(x['January'])

我得到的错误是

    KeyError                                  Traceback (most recent call 
last)
<ipython-input-42-879788f99587> in <module>()
 23 
 24 for x in dict_month:
---> 25     jan_month.append(x['January'])
     26 

 KeyError: 'January'

代码在哪里错了?我该如何纠正呢?

  

输出   [阳光,太阳,太阳]

编辑 its a key error这应该会有所帮助。

3 个答案:

答案 0 :(得分:2)

希望它可以帮到你:

dict_month = [{'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}]  

jan_month =  [x['January'] for x in dict_month]

>>>['Sun', 'Sun', 'Sun', 'Sun']

答案 1 :(得分:1)

dict_month是一个dicts列表,值可以附加在jan_month的新列表中。

>>> dict_month = [{'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}]
>>> jan_month = []
>>> for x in dict_month:
...     jan_month.append(x['January'])
...
>>> jan_month
['Sun', 'Sun', 'Sun', 'Sun']

答案 2 :(得分:0)

[{'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}]

不是dict

dict {}

中的内容
 {'January': 'Sun', 'January': 'Sun','January': 'Sun','January': 'Sun'}

应该是你的词典

[] 中的任何内容都是列表

技术上如此

[{'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}]

是一个列表,列表中的每个项目都是一个带有 1键,值对

的词典
x = [{'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}]

xyz = []

for y in x:
     xyz.append(y['January'])

print(xyz)