Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add to python dictionary without replacing

the current code I have is category1[name]=(number) however if the same name comes up the value in the dictionary is replaced by the new number how would I make it so instead of the value being replaced the original value is kept and the new value is also added, giving the key two values now, thanks.

like image 236
jsnabs2 Avatar asked Sep 29 '22 11:09

jsnabs2


1 Answers

You would have to make the dictionary point to lists instead of numbers, for example if you had two numbers for category cat1:

categories["cat1"] = [21, 78]

To make sure you add the new numbers to the list rather than replacing them, check it's in there first before adding it:

cat_val = # Some value
if cat_key in categories:
    categories[cat_key].append(cat_val)
else:
    # Initialise it to a list containing one item
    categories[cat_key] = [cat_val]

To access the values, you simply use categories[cat_key] which would return [12] if there was one key with the value 12, and [12, 95] if there were two values for that key.

Note that if you don't want to store duplicate keys you can use a set rather than a list:

cat_val = # Some value
if cat_key in categories:
    categories[cat_key].add(cat_val)
else:
    # Initialise it to a set containing one item
    categories[cat_key] = set(cat_val)
like image 54
Will Richardson Avatar answered Oct 06 '22 01:10

Will Richardson