-1

I have a dictionary with repeated keys but different values for those keys and i want to pull all values for a specific key. Here is the abbreviated version of what I mean:

x_table = {'A':'GCT','A':'GCC','A':'GCA','A':'GCG'}

AA_list = [{'A'}]

for aa in AA_list:
    if aa in x_table:
        print x_table[aa]

For some reason it will only pull one of the values from x_table.

Thanks for the help.

dk09
  • 87
  • 1
  • 1
  • 7
  • 5
    a dictionary can not have repeated key. – eyllanesc Mar 20 '18 at 02:26
  • A dict can only have have one value per key, you need to put all the different values in a list (or any container of your choice) and use this as the value. – Julien Mar 20 '18 at 02:27

3 Answers3

1

A dictionary cannot have multiple entries for the same key.
Think about it - how were you planning on accessing the value?
what should x_table['A'] return? 'GCT' or maybe 'GCA'?

What you can do, is make a slight change to you data structure and save a list rather than a single values.
e.g.: x_table = {'A':['GCT','GCC','GCA','GCG'], 'B' = ['some', 'other', 'values']}

In your example - you have only 1 key. From the information you have posted I cannot tell if it is a small sample or the general case. If it is the general case, maybe a list / set / tuple would serve you better: ('GCT','GCC','GCA','GCG')

If you want to understand better why you cannot store multiple entries for the same key, you can read about it in this link.

Avi Turner
  • 10,234
  • 7
  • 48
  • 75
-1

Maybe you need define you dict structure like this:

x_table = {'A':['GCT','GCC','GCA','GCG']}
guichao
  • 198
  • 1
  • 7
-1

So, a dictionary is implemented as a set. As such, you cannot have multiple identical keys like so:

dict = {'a': 'blah', 'b': 'foo', 'b': 'bar'}; // ''b would only have the value 'bar'

The way dictionaries are designed, they don't allow this. They are basically hashmaps, and so allow quick access to the value via a key, but you can only have one key per value. When you assign the second key, it overwrites the first.

You could, however, try implementing a dictionary as your value, like so:

x_table = {'A':{'a_1':GCT','a_2':'GCC','a_3':'GCA','a_4':'GCG'},'B':'blah'}

AA_list = ['A']['a_1]

Rezkin
  • 441
  • 1
  • 6
  • 17