Chris D'mello
Chris D'mello

Reputation: 155

Error while Iterating through a list

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

Thats my dict.

My code to make a list of values of 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'])

The error i get is

    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'

Where is the code wrong? how do i correct it?

output [sun,sun,sun]

edit its a key error this should help.

Upvotes: 1

Views: 129

Answers (3)

Veera Balla Deva
Veera Balla Deva

Reputation: 788

Hope it may help you:

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

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

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

Upvotes: 2

Sanjeev Siva
Sanjeev Siva

Reputation: 984

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

Is not a dict

a dict is something that is enclosed in {}

 {'January': 'Sun', 'January': 'Sun','January': 'Sun','January': 'Sun'}

Should be your dict

Anything enclosed in a [] is a list

So technically

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

is a list, and each item of the list is a dict with 1 key,value pair

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

xyz = []

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

print(xyz)

Upvotes: 1

Fasiha
Fasiha

Reputation: 11

dict_month is a list of dicts and values can be append in a new list which is 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']

Upvotes: 1

Related Questions