Solve duplicate items in Dict in Python 3

Asked

Viewed 1,247 times

0

I’m having trouble with my dict. I need it not to delete duplicate key values. I have a style tuple 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 command dict(lista_tuplas) he turns into: {1: [1, 2, 3, 4], 2: [5, 6, 7], 3: [10, 11, 12], 4: [13, 14, 15]}, soon, he replaced the duplicate key that was the 4 by the last value found. How do I avoid this? It is mandatory that I keep both because although they are equal keys, the values between the keys are different! Help Please 0/ is urgent rsrs

  • One of the ways I thought was to do the following: first to go through the lista_tupla and for every equal key found, add a value to it by searching everyone with everyone, then it would look like this: lista_tupla = [(1, [1, 2, 3, 4]), (2, [5, 6, 7]), (3, [7, 8, 9]), (3, [10, 11, 12]), (4.0001, [13, 14, 15])] But I don’t know how to do that because in fact every key of mine is a float, because it’s the result of an average. So adding a very small value is no problem.

  • 2

    But a dictionary with duplicate keys makes no sense. Why do you think you need a dictionary?

  • To convert into dictionary, either you join the values of the repeating keys, or do not use dictionary.

  • It would be interesting if I could clarify how to proceed in the event of a key conflict.

1 answer

1

You didn’t 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 itself another tuple, or even another dictionary, with various other data inside.

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

Then to concatenate its values into large lists in the case of repeated keys:

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

Now, if you don’t want to concatenate the contents of the Dioncarians, but make each dictionary value a list whose items are the other lists of values in their original sequence (that way you preserve the independence of these sequences), just swap the last line above for:

     meu_dict.set_default(chave, []).append(valor)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.