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

你。 提交于 2019-12-05 18:45:49

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)]}

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))

A dictionary value can't contain two tuples just by themselves. Each dictionary key maps to a single value, so the only way you can have two separate tuples associated with that key is for them to be themselves contained within a tuple or list: {'Key1':[(1.000,2.003,3.0029),(2.3232,13.5232,1325.123)]} - note the extra pair of square brackets.

One way of doing this would be to get the current value associated with your key, and append it to a list before setting the new list back to that key. But if there's a possibility you'll need that for any key, you should do it for all keys right at the start, otherwise you'll get into all sorts of difficulties working out what level you're at.

Instead of:

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

What you want is:

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

When you add another tuple, you'll get:

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

I think your questions is somewhat badly formulated. You want to:

  1. Associate a tuple to a key, if the key is not in the dictionary
  2. Replace the tuple with a list of two tuples, if the key is in the dictionary and points to a tuple
  3. Append a tuple to the list of tuples associated to a key

This could 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)

As we know tuples are not mutuable. Instead of using a tuple of tuples. Use list of tuples this will work.

first create a list of tuples and then append it to a dictionay key.\

dictionary = {}
listoftuples = []//create a tuples of list
dictionary[key].append(listoftuples)//appending it to a dictionary key 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!