0

So,I need to iterate over a dictionary in python where the keys are a tuple and the values are integers. I only need to print out the keys and values. I tried this:

for key,value in dict:

but didn't work because it assigned the first element of the tuple to the key and value and the second to the value.

So how should I do it?

4 Answers4

1

Your assumption that for key,value in dict iterates over keys and values at the same time is false. You need to do

for key in dict:
    print("key: " + key)
    print("value: " + dict[key])

or if you feel fancy:

for key,value in dict.items():
    print("key: " + key)
    print("value: " + value)

if you need both keys in the tuple you can also do

for (key1, key2),value in dict.items():
    print("key1: " + key1)
    print("key2: " + key2)
    print("value: " + value)
peer
  • 4,171
  • 8
  • 42
  • 73
1

Just use for key in dict and then access the value with dict[key]

0

Try something like:

for item in a_dict.items():
   print(item)

you will see it print a tuple that is the key and value, item[0] should be your touble and item[1] should be the value stored under that key.

LhasaDad
  • 1,786
  • 1
  • 12
  • 19
0
# regarding a proposed edit:
# dict() can be used to initialize a dict from different formats
# it accepts for instance a dict or a list of tuples
# in case of a static dict like below, only using {..} is sufficient
dot = dict({
  ('a', 'b'): 1,
  ('c', 'd'): 2
})

for k, v in dot.items():
   print(k,  " and ", v)
hootnot
  • 1,005
  • 8
  • 13