hokie1999
hokie1999

Reputation: 1

Append values to keys in python dictionary

I am getting an error

AttributeError: 'unicode' object has no attribute 'append'

for the following python code:

getStats pulls system info and places it in several keys of dictionary, each with one value, writes dictionary to json file, and script stops. script wakes up hourly, reads json file, takes new getStats sample and should append those new values to appropriate keys, creating lists.

Here's the essence of the script:

newDict = getStats()
.
.
. 
oldDict['offset'].append(newDict['offset'])
(Attribute error occurs here)

I have a workaround that iterates through the keys' value list, creates new list, appends new value to new list, and writes to appropriate key in oldDict. Seems klunky....was wondering if there is something missing here.

Here is my json file on first iteration of script:

{"maxError": "275848", "pollingInterval": "512", "timeCorrect": "57", "driftTime": "21.056", "frequency": "21.099", "offset": "288.840"}

Thanks for help!

Upvotes: 0

Views: 601

Answers (3)

vash_the_stampede
vash_the_stampede

Reputation: 4606

If you wanted to copy every key and value from one dictionary to a new one, I would use this:

oldDict = {} 
oldDict['offset'] = 'some_value'

newDict = {}

for key, value in oldDict.items():
   newDict[key] = value

If you wanted to copy only a specific set of keys with their value, you could use something like this:

oldDict = {}
oldDict['offset'] = 'some_value'
oldDict['other'] = 'other_value'

newDict = {}

for key, value in oldDict.items():
    if key == 'offset':
        newDict[key] = value

This would only add the key and value if it was 'offset'

Upvotes: 0

k.wahome
k.wahome

Reputation: 1062

oldDict['offset'] must hold a type that has no attribute append.

Most likely a string evident from the shared json:

{"maxError": "275848", "pollingInterval": "512", "timeCorrect": "57", "driftTime": "21.056", "frequency": "21.099", "offset": "288.840"}

Reproduction of the issue:

>>> oldDict = {"offset": "1"}
>>> newDict = {"offset": "2"}
>>> oldDict["offset"].append(newDict["offset"])
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'

You need to represent it as a list to use append:

>>> oldDict['offset'] = []
>>> oldDict['offset'].append(newDict['offset'])

Be careful with what you pass to append(). If you give it another list which is what newDict["offset"] will have if you go the list way in getStats(), it will add the list at the end of the list in oldDict['offset']

>>> oldDict = {"offset": ["1"]}
>>> oldDict["offset"]
['1']
>>> newDict = {"offset": ["2"]}
>>> newDict["offset"]
['2']
>>> oldDict["offset"].append(newDict["offset"]) 
>>> oldDict["offset"]
['1', ['2']]

You instead need to pass the value(s) if you are looking to only add the value(s) of newDict["offset"] into in oldDict["offset"] in which case you may need list comprehension:

>>> oldDict = {"offset": ["1"]}
>>> oldDict["offset"]
['1']
>>> newDict = {"offset": ["2"]}
>>> newDict["offset"]
['2']
>>> [oldDict["offset"].append(item) for item in newDict["offset"]]
[None]
>>> oldDict["offset"]
['1', '2']

or simply use + on the lists:

>>> oldDict = {"offset": ["1"]}
>>> newDict = {"offset": ["2"]}
>>> oldDict["offset"] + newDict["offset"]
['1', '2']

Upvotes: 0

gxor
gxor

Reputation: 363

The value of the dict['offset'] is a string. You should make it a list if you want to append the new offset. Where you initialize you oldDict, try this:

dict['offset'] = []
dict['offset'].append(newDict['offset']) 

Upvotes: 3

Related Questions