0

I want to iterate through this dictionary of dictionary. Ultimately I want to divide up the values from each dict.. e.g., 0.5/0.4, 0.3/0.2, and 0.1/0.1 to find the max, but I haven't reached there yet. Any help with the iteration would be appreciated.

#!/usr/bin/env python2

dict = {('a', 0.5): ('b', 0.4), ('c', 0.3): ("d", 0.2), ('e', 0.1): ('f', 0.1)}

for keys, values in dict:
    print "key: %s" % keys
    print "values: %f" % values
    for keys1, values1 in dict[keys]:
        print "key1: %s" % keys1
        print "values1: %f" % values1

However I get an error:

key: a values: 0.500000 Traceback (most recent call last):
File "test.py", line 8, in for keys1, values1 in dict[keys]: KeyError: 'a'

O_O
  • 4,397
  • 18
  • 54
  • 69

4 Answers4

6

First rename your variable dict to d.

This is not dictionary of dictionary. This is dictionary containing tuples as key, and values.

for k, v in d.items():
    a = k[1]
    b = v[1]
    print(a/b)
Rahul
  • 10,830
  • 4
  • 53
  • 88
2

A simple for loop works here:

In [1169]: for d in dict_:
      ...:     print(d[-1], '/', dict_[d][-1])
      ...:     
0.5 / 0.4
0.3 / 0.2
0.1 / 0.1

Some considerations -

  1. Both your keys and values are tuples, so use [-1] to index the last element in each case

  2. Preferably don't use dict.items() because it creates a copy of the dict in memory to iterate over

  3. Do not use dict as a variable name, it shadows the builtin dict

cs95
  • 379,657
  • 97
  • 704
  • 746
2
dict = {('a', 0.5): ('b', 0.4), ('c', 0.3): ("d", 0.2), ('e', 0.1): ('f', 0.1)}

for key, value in dict.iteritems():
    print "key=", key
    print "value=",value
    print "division=",key[1]/value[1]

Output

key= ('a', 0.5)
value= ('b', 0.4)
division= 1.25
key= ('c', 0.3)
value= ('d', 0.2)
division= 1.5
key= ('e', 0.1)
value= ('f', 0.1)
division= 1.0
Alpesh Valaki
  • 1,611
  • 1
  • 16
  • 36
1

to iterate over a Dictionary you need to call the function ״iteritems():״ ( in Python 2.7) you can read more about it here

Iterating over dictionaries using 'for' loops

dicte = {('a', 0.5): ('b', 0.4), ('c', 0.3): ("d", 0.2), ('e', 0.1): ('f', 0.1)}
for keys, values in dicte.iteritems():
    print "key: {}".format(keys)
    print "values: {}".format(values)
    keys1, values1 = keys
    print "key1: {}".format(keys1)
    print "values1: {}".format(values1)
noam stein
  • 11
  • 2