How to append to a dictionary? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to append to a dictionary? (/thread-24219.html) |
How to append to a dictionary? - t4keheart - Feb-04-2020 Hi everyone, This seems like it should be simple, I just don't know how to do it. Anyways, I'm working with a json response from a server/api. I would like to store 2 data points to a dictionary of lists (? i think, list of lists?). The problem is, instead of appending it's overwriting, so assume there are 10 json objects in the response with a key (id) & value (message)- when I print(dictionary) I only get 1 result like this: {1038374: 'test message10'}Whereas my desired output when printing the dictionary is like this: {1028374: 'test msg1', 384759: 'test msg2', 4384573: 'test msg3'... and so on }Here is my for loop: r=requests.get(url + id, headers=h, params=p) inbound_dict = {} inbound=json.loads(r.text) for item in inbound['messages']: inbound_dict[item['conversationId']] = item['body'] print(inbound_dict)What am I doing incorrectly with my loop? How do I get it to append to a dictionary of lists instead of overwriting? Finally, how would I then store those key/values to an object to reference later in another function? If say, I wanted to pull message 3, from the middle. Thank you for reading! I forgot to add- I think I know what the issue is with this, the "key" is not unique, and is shared amongst all of the values... so I believe this needs to be a list of lists, rather than a dictionary. But when I try to do so, I get errors about the index being out of range. Trying to do something with this: response=requests.get(url + id, headers=h, params=p) messages=json.loads(response.text) for message in messages: print(message['id'])...thinking it might get me closer to what I need to accomplish. I need to somehow organize this data and store it to be used somewhere in the future for reference, and it's proving to be quite the task. RE: How to append to a dictionary? - t4keheart - Feb-05-2020 I solved this issue! Here's what ended up working for me... response=requests.get(url + id, headers=h, params=p).json() inbound_dict = {} for item in response['messages']: conv_id = item['conversationId'] if conv_id not in inbound_dict: inbound_dict[conv_id]={item['id'] : {'msg_id' : item['id'], 'body' : item['body']}} else: inbound_dict[conv_id][item['id']] = {'msg_id' : item['id'], 'body' : item['body']} pprint(inbound_dict) |