smet for
smet for

Reputation: 11

Get value from dictionaries in a dictionary

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.

Upvotes: 0

Views: 38

Answers (3)

snakecharmerb
snakecharmerb

Reputation: 55799

You don't care about the keys in the outer dictionary, so iterate over the values:

for v in x.values():
    print(v['number'])

Upvotes: 0

Viliam Popovec
Viliam Popovec

Reputation: 310

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.

Upvotes: 1

Gagan Mishra
Gagan Mishra

Reputation: 25

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 :)

Upvotes: 1

Related Questions