Python Forum
How to append to a dictionary?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to append to a dictionary?
#1
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! Pray Wall LOL

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.
Reply
#2
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Cant Append a word in a line to a list err "str obj has no attribute append Sutsro 2 2,567 Apr-22-2020, 01:01 PM
Last Post: deanhystad
  Iterate through a list of dictionary and append a new value. erina 1 2,095 May-16-2019, 09:55 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020