I have a dictionary of dictionaries with numbers inside. I would like to get all numbers from different named dictionaries(string).
x={"stringdict1":{"number":56},"stringdictx":{"number":48}}
I'm looking for this: 56, 48.
It is not clear to me how I can get inside different "stringed" dictionaries. I tried this (and a few other silly variations):
for numbers in dict[:]:
print(numbers)
The problem for me is the different names(str) of the dictionary titles, but containing the same keys inside.
CodePudding user response:
Iterate over the dictionary items
and check for the number key inside the sub-dictionaries.
for key, sub_dict in x.items():
print(sub_dict['number'])
P.S. Don't use dict
as variable name, you would overwrite the built-in functionality.
CodePudding user response:
Okay so you will have to use nested for loop in order to get the inner value of a dictionary. Try this:
x={"stringdict1":{"number":56},
"stringdictx":{"number":48}}
for i in x:
for j in x[i]:
print(x[i][j])
Do let me know if you find a better solution, as this is not very efficient with respect to the time and space complexities :)
CodePudding user response:
You don't care about the keys in the outer dictionary, so iterate over the values:
for v in x.values():
print(v['number'])