Home > other >  python string named dictionaries for loop
python string named dictionaries for loop

Time:10-08

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. I hope I'm clear. Can I have some advice please?

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

  • Related