Solve duplicate items in dict in Python 3

0

I'm having problems with my dict . I need it not to delete the duplicate key values. I have a tuple style lista_tupla = [(1, [1, 2, 3, 4]), (2, [5, 6, 7]), (3, [7, 8, 9]), (3, [10, 11, 12]), (4, [13, 14, 15])] but when I use the dict(lista_tuplas) it turns it into: {1: [1, 2, 3, 4], 2: [5, 6, 7], 3: [10, 11, 12], 4: [13, 14, 15]} , so it replaced the duplicate key that was 4 with the last value found. How do I avoid this? It is mandatory for me to keep both, because although they are equal keys, the values between the keys are different! Help please \ 0 / is urgent rsrs

    
asked by anonymous 17.07.2016 / 17:47

1 answer

0

You did not say the most important thing: what to do when you find duplicate keys! A dictionary has to have distinct keys - but nothing prevents each value from being another tuple, or even another dictionary, with several other data inside.

So if you want the dictionary to be a single list, with the values in your list concatenated, you can do a congo using the setdefault method of dictionaries: this method returns the value associated with a key, if it already exists - if it does not exist, it associates the second parameter passed as value for that key, and returns the same. That is, meudict.setdefault("chave", []) returns the value that is in meudict["chave"] , or places an empty list in meudict["chave"] and returns that list - which we can then manipulate with append or extend.

Then to concatenate your values in large lists in case of repeated keys:

meu_dict = {}
for chave, valor in lista_tupla:
     meu_dict.set_default(chave, []).extend(valor)

Now, if you do not want to concatenate the content of the dictionary, but make each dictionary value a list whose items are the other lists of values in its original sequence (this way you preserve the independence of those sequences), just change the last line above by:

     meu_dict.set_default(chave, []).append(valor)
    
18.07.2016 / 14:55