0

I have a dictionary consisting of 4 keys with 3 values per key.

Looks like this: d = {key1: (value1, value2, value), key2: (value1, value2, value), key3: (value1, value 2, value3)}

I want to print value1 from all of the keys. The way I have done it now is like this:

print (persons['1'][0])
print(persons['2'][0])
print (persons['3'][0])
print(persons['4'][0])

But I guess there is an easier way so that I can refer to all the keys in just one line? I also want to find the highest value2 in all the keys, and the average from value3 in all keys. Can someone please help me with this?

buran
  • 13,682
  • 10
  • 36
  • 61
  • Does this answer your question? [Iterating over dictionaries using 'for' loops](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) – buran Sep 16 '20 at 08:02

5 Answers5

0

You can use for loop to iterate:

d = {'test1': (1, 2, 3), 'test2': (4, 5, 6), 'test3': (7, 8, 9)}
for key in d.values():
    print(key[0])
Sam Dani
  • 114
  • 1
  • 6
0

what about?

d = {
    "key1": (1,2,3),
    "key2": (3,4,5),
    "key4": (5,6,8),
}

[ print(val[0]) for _, val in d.items()]
Sergey Grechin
  • 876
  • 11
  • 14
0

Try this bro:

d = {"key1": (5, 2, 6), "key2": (6, 7, 3), "key3": (5, 7, 9)}
for i in d:
    print(d[i][0])
thống nguyễn
  • 765
  • 1
  • 5
  • 13
0

you can achive this using list comprehension:

persons = {'1': (1,2,3), '2': (4,5,6), '3': (7,8,9)}

# First Value's
first_values = " ".join([str(x[0]) for x in persons.values()])
print(first_values)   # prints 1 4 7

# Max of second value's
max_value2 = max([x[1] for x in persons.values()])
print(max_value2)  # prints 8

# Average of value3's
third_values = [x[2] for x in persons.values()]
average_of_third_values = sum(third_values) / len(third_values)

# in case avoid zero division  : 
# average_of_third_values = sum(third_values) / (len(third_values) or 1)

print(average_of_third_values)  # prints 6

# to get value1 of values which has max value2
value1_of_max = [x[0] for x in persons.values() if x[1]==max_value2]
print(value1_of_max)  # prints [7]
# Its possible to be exist more than 1 person that has value2 which equals to max number, like so
# persons = {'1': (1,2,3), '2': (4,8,6), '3': (7,8,9)}
# so we print them as list
AbbasEbadian
  • 653
  • 5
  • 15
  • do you also know how I could print value1 for the max value2? So since max value2 is 8 in your example, python would print value 1 (7) from that key? – Silje Bue Sep 16 '20 at 10:36
  • @SiljeBue Glad i could help.If you found it helpful ill appreciate if you upvote and make it accepted answer if it does answer. Thank you. – AbbasEbadian Sep 16 '20 at 11:37
0

You can convert your dict into a DataFrame which will make things very easy for you:

from pandas.DataFrame import from_dict
d = {'a':(1,2,3),'b':(4,5,6)}
d = from_dict(d, orient='index')
d[0] # print values of value1
d[1].max() # max of value2
d[2].mean() # mean of value3
Tanveer
  • 51
  • 1
  • 1
  • 7