简体   繁体   中英

python updating dictionary with list as the value type

I'm trying to iterate through data extracted from a file and store them in a dictionary based on each data's id

These are the id (str) for the data : "sensor", "version", "frame", "function"

And the data are in hexadecimal string.

What I bascially start with is a huge list of tuples in a form of id and data (that i extracted from a file)

example_list = [("sensor", 245), ("frame", 455), ("frame", 77)] and so on

This example_list stores all the data, so it has information of data for all the id.
I want to make a dictionary with id as key and list of data as value so when done iterating through the example_list, I have list of values for specific id (so I can iterate through the value list to get all the data for a specific id (the key))

To start, all values (list) will start with an empty list

my_dict = {"sensor": [], "frame": [], "version": [], "function": []}

Then, as I iterate through example_list, if the id is in my_dict as a key, I append the value to the values list in my_dict

for itm in example_list:
    if itm[0] in my_dict:
        tmp = my_dict[itm[0]] # since itm[0] is the id
        tmp.append(itm[1])
        my_dict[itm[0]] = tmp # update the list 

When I tried this, it seems like the final my_dict's value list has the value of the lastest data What I mean by this is if

example_list = [("sensor", 245), ("frame", 455), ("frame", 77)] 

then

my_dict = {"sensor": [245], "frame": [77], "version": [], "function": []}

I may be wrong about this interpretation (since the data I'm reading is really big), but when I printed my_dict in the end of function, each value list had only one data inside, which is far off from what I expected (list of data instead of just one)

I tried searching and people used update function to update the dictionary but that one also didn't seem to work and gave me somehting unhashable error/warning.

Any way to implement what I want to do?

try doing it like so:

for itm in example_list:
    if itm[0] in my_dict:
        my_dict[itm[0]].append(itm[1])

Your code is working as required. To simplify, as you've already instantiated the dict with empty lists:

for i,j in example_list:
    my_dict[i].append(j)
print(my_dict)

Output:

{'sensor': [245], 'frame': [455, 77], 'version': [], 'function': []}

What you want to do is:

for itm in example_list:
    if itm[0] in my_dict.keys(): # have to look if keys match
        my_dict[itm[0]].append(itm[1]) # # directly access the key-value pair

Your problem was that you created a new list and appended your item to it each time the loop was run, therefore the old data was deleted everytime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM