0

I'm collecting weather data and trying to create a list that has the latest (temperature) value by minute.

I want to add them to a list, and if the list does not contains the "minute index" it should at it as a new element in the list. So the list always keeps the latest temperature value per minute:

def AddValue(arr, value):
    timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M")

    for v in arr['values']:
        try:
            e = v[timestamp]     # will trigger the try/catch if not there
            v[timestamp] = value
        except KeyError:
            v.append({ timestamp: value })

history = [
    { 'values': [ {'2017-12-22 10:20': 1}, {'2017-12-22 10:21': 2}, {'2017-12-22 10:22': 3} ] },
]

AddValue(history, 99)

However, I'm getting

AttributeError: 'dict' object has no attribute 'append'**
4
  • 1
    What's the point of a dictionary if you have to iterate over it? Also, you're creating a timestamp on the fly. What are the odds that the Key already exists? Commented Dec 22, 2017 at 10:51
  • I don't get why you want to trigger the except if the key is not there. Commented Dec 22, 2017 at 10:53
  • Furthermore I don't see what this has to do with JSON. Commented Dec 22, 2017 at 10:53
  • for v in arr['values']: don't think it works because your history is list.. Commented Dec 22, 2017 at 10:56

1 Answer 1

2

You associate a key k with a value v in a dictionary d with:

d[k] = v

this works regardless whether there is already a key k present in the dictioanry. In case that happens, the value is "overwritten". We can thus rewrite the for loop to:

for v in arr['values']:
    v[timestamp] = value

In case you want to update a dictionary with several keys, you can use .update and pass a dictionary object, or named parameters as keys (and the corresponding values as value). So we can write it as:

for v in arr['values']:
    v.update({timestamp: value})

which is semantically the same, but will require more computational effort.

Nevertheless since you need to iterate over a dictionary, you perhaps should reconsider the way you structured the data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.