Combine nested dict items to a string

oliverbj

I have below nested dict d:

{
 1: {1: {'text': 'Contact', 'x0': Decimal('21.600')}},
 2: {1: {'text': 'My mail is', 'x0': Decimal('21.600')},
     2: {'text': '[email protected]', 'x0': Decimal('223.560')}}
}

I am trying to "combine" the nested dictionaries for each top-level key into a string (that should form a sentence). For example:

1: Contact
2: My mail is [email protected]

So I am a bit in doubt on how to do this in Python. This is what I have currently:

for line in d:
    for word_no, text in d[line].items():
        print(text['text'])

This prints each text string, but doesn't combine anything. Can anyone guide me in the right direction?

Rakesh

You just need another iteration.

Ex:

from decimal import Decimal

d = {
 1: {1: {'text': 'Contact', 'x0': Decimal('21.600')}},
 2: {1: {'text': 'My mail is', 'x0': Decimal('21.600')},
     2: {'text': '[email protected]', 'x0': Decimal('223.560')}}
}

for k, v in d.items():
    print("{}: {}".format(k, " ".join(n["text"] for _, n in v.items())))   #Combine "text"

Output:

1: Contact
2: My mail is [email protected]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related