1

I have a dictionary that has many values per key. How do I print a specific value from that key?

for example, my key is "CHMI" but it has 14 values associated with it. How do I print only CHMI: 48680 value?

CHMI: ['CHMI', '16', '16.09', '15.92', '16.01', '0.02', '0.13', '48680', '17.26', '12.6', '1.96', '12.24', '14.04', '23.15']
styvane
  • 59,869
  • 19
  • 150
  • 156
Deuce525
  • 77
  • 1
  • 2
  • 10

3 Answers3

5

You have a dictionary with a key:value pair where the value is a list.

To reference values within this list, you do your normal dictionary reference, ie

 dict['chmi']

But you need to add a way to manipulate your list. You can use any of the list methods, or just use a list slice, ie

dict['chmi'][0] 

will return the first element of the list referenced by key chmi. You can use

dict['chmi'][dict['chmi'].index('48680')]

to reference the 48680 element. What I am doing here is calling the

list.index(ele) 

method, which returns the index of your element, then I am referencing the element by using a slice.

jay
  • 493
  • 1
  • 3
  • 11
  • Thanks I got it to work! I had tried that syntax before but didn't work but i think i was missing parenthesis or something. – Deuce525 Jun 24 '16 at 18:32
0

Although I don't understand why you would want to do it (if you already know what value you want, why not use it directly?), it can be done with the index method of lists, which returns the index of the provided value in the list

d = {'CHMI': ['CHMI', '16', '16.09', '15.92', '16.01', '0.02', '0.13', '48680', '17.26', '12.6', '1.96', '12.24', '14.04', '23.15']}

chmi_values = d['CHMI']

print(chmi_values[chmi_values.index('48680')])
>> '48680'
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

Do you want the 8th element of the list, or an element with a specific value? If you already know the value - then you can print it without looking it up in the list so I assume you want to just retrieve one of the elements:

print(my_dict['CHMI'][7])

This is equivalent to:

values = my_dict['CHMI']
eight_value = my_dict[7]
print(eigth_value)

If this is not what you need, I'm afraid you'll have to clarify your question a little :)

André Laszlo
  • 15,169
  • 3
  • 63
  • 81
  • I would like the eigth value of my list. I actually have over 2,000 keys in my dictionary and each one has a different value at the 8th element, so i am trying to determine how to access that index value specifically so eventually i can run loop for each key and "do something" to that 8th element – Deuce525 Jun 24 '16 at 18:31
  • Ok then you should have a solution above ☺️ – André Laszlo Jun 24 '16 at 18:32