-2

I'm writing code and I know that a key in a python dictionary can have multiple values, but how can I refer to the desired value by its index? I want to get all first values from all keys from dict. My dictionary:

ip = {'18992549780':[764890830,10000], '18992548863':[764890926,20000]}

But my solution throws an error:

print(ip.values().index[0])

AttributeError: 'dict_values' object has no attribute 'index'

2 Answers2

0

To get all first values from all keys from that dictionary, you should use something as the following:

result = [list_[0] for list_ in ip.values()]
print(result)

output

[764890830, 764890926]

explanation

We're just using list comprehension to iterate over the values() object of the ip dictionary. Then, for each value (in this case: list) of each key of the dictionary, we're appending the first element (list_[0]) to our result list.

revliscano
  • 2,227
  • 2
  • 12
  • 21
0

"I know that a key in a python dictionary can have multiple values"

No, it can't. It may have a list as a value, and that list may contain several elements.

If you want to get all the first elements in all the values you'd need to iterate over the values and grab the correct index:

for values_list in ip.values():
    print(values_list[0])

If you want to collect all of them in a list:

first_values = [values_list[0] for values_list in ip.values()]

Be careful: if some lists are empty an IndexError will be raised. If this may be the case I'd need to use a try-except.

Unless you are using Python 3.7 and above, you must not rely on the order of the elements in the constructed list as dictionaries are unordered prior to 3.7.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154