Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add multiple tuples(lists, whatever) to a single dictionary key without merging them?

I've been trying to figure out how to add multiple tuples that contain multiple values to to a single key in a dictionary. But with no success so far. I can add the values to a tuple or list, but I can't figure out how to add a tuple so that the key will now have 2 tuples containing values, as opposed to one tuple with all of them.

For instance say the dictionary = {'Key1':(1.000,2.003,3.0029)}

and I want to add (2.3232,13.5232,1325.123) so that I end up with:

dictionary = {'Key1':((1.000,2.003,3.0029),(2.3232,13.5232,1325.123))} (forgot a set of brackets!)

If someone knows how this can be done I'd appreciate the help as it's really starting to annoy me now.

Thanks!

Edit: Thanks everyone! Ironic that I tried that except at the time I was trying to make the value multiple lists instead of multiple tuples; when the solution was to just enclose the tuples in a list. Ah the irony.

like image 302
Jason White Avatar asked Nov 29 '22 09:11

Jason White


2 Answers

Use defaultdict and always use append and this will be seemless.

from collections import defaultdict

x = defaultdict(list)
x['Key1'].append((1.000,2.003,3.0029))
like image 117
Nix Avatar answered Dec 05 '22 04:12

Nix


Just map your key to a list, and append tuples to the list.

d = {'Key1': [(1.000,2.003,3.0029)]}

Then later..

d['Key1'].append((2.3232,13.5232,1325.123))

Now you have:

{'Key1': [(1.0, 2.003, 3.0029), (2.3232, 13.5232, 1325.123)]}
like image 26
Charles Salvia Avatar answered Dec 05 '22 03:12

Charles Salvia