Print a dictionary with the given format

138 Views Asked by At

Here is my code. It is necessary to output with preservation of text formatting and changes made to the dictionary

from pprint import pprint
site = {
    'html': {
        'head': {
            'title': 'Куплю/продам телефон недорого'
        },
        'body': {
            'h2': 'У нас самая низкая цена на iphone',
            'div': 'Купить',
            'p': 'продать'
        }
    }
}
def find_key(struct, key, meaning):
    if key in struct:
        struct[key] = meaning
        return site
    for sub_struct in struct.values():
        if isinstance(sub_struct, dict):
            result = find_key(sub_struct, key, meaning)
            if result:
                return site
number_sites = int(input('Сколько сайтов: '))
for _ in range(number_sites):
    product_name = input('Введите название продукта для нового сайта: ')
    key = {'title': f'Куплю/продам {product_name} недорого', 'h2': f'У нас самая низкая цена на {product_name}'}
    for i in key:
        find_key(site, i, key[i])
    print(f'Сайт для {product_name}:')
    pprint(site)

Doesn't show full dictionary

3

There are 3 best solutions below

3
On BEST ANSWER

This should work

import json

print(json.dumps(site, indent=4, ensure_ascii=False))

6
On

Possible solution is the following:

import json

number_sites = int(input('Сколько сайтов: '))

for _ in range(number_sites):
    site = {'html':{
        'head':{'title': 'Куплю/продам телефон недорого'},
        'body':{'h2': 'У нас самая низкая цена на iphone','div': 'Купить', 'p': 'продать'}}}
    product_name = input('Введите название продукта для нового сайта: ')
    key = {'title': f'Куплю/продам {product_name} недорого', 'h2': f'У нас самая низкая цена на {product_name}'}
    
    site.get('html', {}).get('body', {})['h2'] = key['h2']
    site.get('html', {}).get('head', {})['title'] = key['title']
    
    print(f'\nСайт для {product_name}:')
    print('site =')
    print(json.dumps(site, indent=4, ensure_ascii=False))

Returns

Сколько сайтов: 1
Введите название продукта для нового сайта: IPHONE

Сайт для IPHONE:
site =
{
    "html": {
        "head": {
            "title": "Куплю/продам IPHONE недорого"
        },
        "body": {
            "h2": "У нас самая низкая цена на IPHONE",
            "div": "Купить",
            "p": "продать"
        }
    }
}
0
On
#import json

data = json.dumps(site, ensure_ascii=False, indent=4)
print("site = " + data.replace('"', "'"))

That's how perfect it was