Reputation: 19
Can someone please tell me what basic thing I am missing here.
Type: <class 'list'>
Value : ['09,10,11,12,13,14,15']
for datapoint in value:
y.append(datetime.fromtimestamp(datapoint).strftime('%I%P').lstrip('0').upper())
I want value of y should be like this-[9PM,10PM,11PM,12PM,1PM,2PM,3PM]
I am not sure why its is not converting to the value I want, if I am using above function. Can someone please suggest what I am missing here and why I am getting this error -> "AttributeError: 'dict' object has no attribute 'append'"
Upvotes: 0
Views: 6738
Reputation: 51663
You have a 1-element list with a string in it: your datapoint
is the single whole string, not pieces of it. You need to split and iterate over the splitted values:
from datetime import datetime
y = [] # use list to use append, see dict approach below
data = '09,10,11,12,13,14,15'.split(",") #split into ["09","10",...,"15"]
for dp in data: # "09" then "10" then "11" etc.
y.append(datetime.strptime(dp,"%H").strftime('%I%P').strip("0").upper())
print(y)
Output:
['9AM', '10AM', '11AM', '12PM', '1PM', '2PM', '3PM']
To add that do a dictionary you need to use update((key,value)-iterable)
or d[key]=value
:
d = {}
for time in y:
d["Time "+time] = time
# or
d.update( ((t,t) for t in y) ) # doesnt make much sense to have identical key/values
# d[]=... - Output
{'Time 9AM': '9AM', 'Time 12PM': '12PM', 'Time 3PM': '3PM',
'Time 11AM': '11AM', 'Time 2PM': '2PM', 'Time 10AM': '10AM',
'Time 1PM': '1PM'}
# update - Output
{'12PM': '12PM', '1PM': '1PM', '11AM': '11AM', '9AM': '9AM',
'10AM': '10AM', '3PM': '3PM', '2PM': '2PM'}
Upvotes: 1
Reputation: 31
The error is pretty clear, you are trying to use append()
on the variable y
which is here a dictionary. Dictionaries do not have an append()
function, hence the error.
In order for your code to work, you probably need y
to be a list
.
Upvotes: 0