-1

Beginner question but I wanted to handle data from multiple dictionaries in a single variable. For example:

x = {"age":"24","name":"Bob"}, {"age":"21","name":"George"}

In this case, how would I find out what "age" is in each dictionary in x, and put them in a list? This should be the desired outcome:

ages = ["24","21"]

This is what I've tried so far but raises an error:

x = {"age":24,"name":"Bob"}, {"age":21,"name":"George"}
ages = []
for y in x:
     ages.append(x["age"])
TypeError: list indices must be integers or slices, not str
mkrieger1
  • 19,194
  • 5
  • 54
  • 65

3 Answers3

0

Use ages.append(y["age"]) - note the y which references each dictionary in the tuple of dictionaries referenced by x

gruntfutuk
  • 16
  • 1
  • 3
0

Maybe because you try and find the key of a tuple? You need to use y.

ages = []
for y in x:
     ages.append(y["age"])
print(ages)
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
-1

You can just check whether the dictionary contains the key you want.

if "age" in y:
    ages.append(y["age"])
Ludal
  • 110
  • 1
  • 7