0
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'"

glibdud
  • 7,550
  • 4
  • 27
  • 37
Terry
  • 19
  • 1
  • 8

2 Answers2

1

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'}
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • I tried the first one but I again getting the attribute error data = value.split(",") #split into ["09","10",...,"15"] AttributeError: 'list' object has no attribute 'split' – Terry Oct 26 '18 at 15:55
  • print(value) ['09,10,11,12,13,14,15,16'] – Terry Oct 26 '18 at 16:02
  • @Terry what do you want to tell me? `data = value[0].split(",")` then rest of the code as above ... – Patrick Artner Oct 26 '18 at 16:57
0

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.