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

I tried to figure out how to add multiple tuples containing multiple values ​​to the same key in the dictionary. But so far nothing has happened. I can add values ​​to a tuple or list, but I cannot figure out how to add a tuple so that the key now has 2 tuples containing values, as opposed to a single tuple with all of them.

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

and I want to add (2.3232,13.5232,1325.123), so that in the end it turns out:

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

If someone knows how to do this, I will be grateful for the help, as it really starts to annoy me.

Thank!

Edit: Thanks everyone! Ironically, I tried this, except that at that time I was trying to make the value of multiple lists instead of multiple tuples; when the solution was to simply nest tuples in a list. Ah, the irony.

+3
source share
6 answers

Use defaultdict and always use append, and that won't matter.

from collections import defaultdict

x = defaultdict(list)
x['Key1'].append((1.000,2.003,3.0029))
+9
source

Just draw your key in the list and add 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)]}
+4
source

. , , , , , : {'Key1':[(1.000,2.003,3.0029),(2.3232,13.5232,1325.123)]} - .

- , , , . , , , , .

+3

:

{'Key1':(1.000,2.003,3.0029)}

:

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

, :

{'Key1':[(1.000,2.003,3.0029), (2.3232,13.5232,1325.123)]}
+1

, . :

  • ,
  • ,
  • ,

This can be achieved with the following code:

def insertTuple(d, k, tup):
    if k not in d:
        d[k] = tup
    elif type(d[k]) == tuple:
        d[k] = [ d[k], tup ]
    else:
        d[k].append(tup)
+1
source

As we know, tuples do not change. Instead of using tuples of tuples. Use a list of tuples, this will work.

first create a list of tuples, and then add it to the word key. \

dictionary = {}
listoftuples = []//create a tuples of list
dictionary[key].append(listoftuples)//appending it to a dictionary key 
0
source

All Articles