'Print a dictionary with the given format
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
Solution 1:[1]
This should work
import json
print(json.dumps(site, indent=4, ensure_ascii=False))
Solution 2:[2]
#import json
data = json.dumps(site, ensure_ascii=False, indent=4)
print("site = " + data.replace('"', "'"))
That's how perfect it was
Solution 3:[3]
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": "???????"
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sam Girshovich |
| Solution 2 | 3Vw |
| Solution 3 |
