-1

Hey guys here´s my problem.

Lets say I have two dictionaries and a list containing both dictionaries:

a={1:"hello",2:"goodbye"}
b={1:"Hi",2:"Farewell"}
list1=[a,b]

Now, if I iterate over the entire list like this, everything works fine:

for e in list1:
    print(e[1])

However, whenever I try to iterate over the list by using the list index number, python throws an error message ("TypeError: 'int' object has no attribute 'getitem'")

for e in list1[0]:
    print(e[1])

Could someone explain how I can access the dictionary value of a certain item in a list with a list index number?

Thanks in advance for your help!

  • 2
    You are trying to ask : Why is `for e in a: print(e[1])` not working given a dictionary `a`. The answer is when you iterate in a dict of `a` like that, your `e`s are the keys. In first iteration - `e` is 1, second, `e` is 2. Now, how can you query `e[1]` on an integer? You can't. What you need to clarify to yourself is: How to iterate inside a dict as key-value pairs. You'll figure out the problem that way easily. – FatihAkici Aug 14 '19 at 14:39
  • 2
    A good practice is: Right after you execute the `for e in list1[0]:` part, you have an `e` in your hand. Always print that object in the first line of the loop. That way, before attempting to subscript it like `e[1]`, you can see what you are working with. – FatihAkici Aug 14 '19 at 14:44

6 Answers6

1

You can try:

a = {1: "hello", 2: "goodbye"}
b = {1: "Hi", 2: "Farewell"}
list1 = [a, b]

for index, dict_data in enumerate(list1):
    print(index)
    print(dict_data)
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
1

the problem is that list1[0] is a dictionary, and when using the way you are doing in a for loop, it'l iterate over the keys of that dictionary

so in your case, for the first iteration the e variable is of type int with the value 1, in the second iteration it has the value 2.

so if you want to iterate over the keys, and values of a dictionary you should use

for key, val in list1[0].items():
    print('key: {}, value {}'.format(key, val))
1

you can use the .get method like this:

for d in list1:
    for i in d:
        print(d.get(i))

maybe this can help you

maxgomes
  • 329
  • 3
  • 12
0

list1[0] is a dict. using for ... in ... on a dict iterates the keys, and your keys are ints.

try:

for e in list1[0]:
    print(e)
    print(list1[0][e])
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
0

Just do:

for e in list1[0]: print(e)

Brozo
  • 277
  • 1
  • 9
-1

Dictionary entries aren't stored in a given order, so the output won't be what you expect. However, you can do next(e.values()).

JoshuaF
  • 1,124
  • 2
  • 9
  • 23