I've tried just about everything to convert a dictionary that looks like this in Python:
d = {'name': 'Jack', 'age': 26}
I know you're able to access values like this:
d['name']
> Jack
I would like to do this in a for loop though:
for obj in d:
print(obj['name'])
Any ideas how? I've tried both json.loads and json.dumps on obj but keep getting errors like: string indices must be integers
. How can I can access specific keys and get their values like the example above?
CodePudding user response:
You need to access .values()
of your main dict
d = {'person-1': {'name':'Jack', 'age':'26'}, 'person-2': {'name':'Idk', 'age':'23'}}
for obj in d.values():
print(obj['name'])
Jack
Idk
And .items()
to get the outer key with
for key, obj in d.items():
print(key, obj['name'])
person-1 Jack
person-2 Idk