Home > Back-end >  Dictionary with dictionaries add numbering to value
Dictionary with dictionaries add numbering to value

Time:11-02

I have a dictionary with dictionaries and I need to add numbers to the values 'plece'. Numbering according to the length of the main dictionary.

{'SVF': {'place': '', 'name': 'Sebastian Vettel', 'team': 'FERRARI', 'time': '1:04.415'}, 'VBM': {'place': '', 'name': 'Valtteri Bottas', 'team': 'MERCEDES', 'time': '1:12.434'}, 'SVM': {'place': '', 'name': 'Stoffel Vandoorne', 'team': 'MCLAREN RENAULT', 'time': '1:12.463'}

Example:

'SVM': {'place': '1', 'name': 'Stoffel Vandoorne', 'team': 'MCLAREN RENAULT', 'time': '1:12.463'}, 'VBM': {'place': '2', 'name': 'Valtteri Bottas', 'team': 'MERCEDES', 'time': '1:12.434'}, 'SVM': {'place': '3', 'name': 'Stoffel Vandoorne', 'team': 'MCLAREN RENAULT', 'time': '1:12.463'} 

CodePudding user response:

You can simply iterate through the values of the outer dictionary(which are dictionaries themselves) and get the numbers from enumerate() object whose start= argument is set to 1:

from pprint import pprint

d = {
    "SVF": {
        "place": "",
        "name": "Sebastian Vettel",
        "team": "FERRARI",
        "time": "1:04.415",
    },
    "VBM": {
        "place": "",
        "name": "Valtteri Bottas",
        "team": "MERCEDES",
        "time": "1:12.434",
    },
    "SVM": {
        "place": "",
        "name": "Stoffel Vandoorne",
        "team": "MCLAREN RENAULT",
        "time": "1:12.463",
    },
}

for i, v in enumerate(d.values(), start=1):
    v["place"] = str(i)

pprint(d, sort_dicts=False)

output:

{'SVF': {'place': '1',
         'name': 'Sebastian Vettel',
         'team': 'FERRARI',
         'time': '1:04.415'},
 'VBM': {'place': '2',
         'name': 'Valtteri Bottas',
         'team': 'MERCEDES',
         'time': '1:12.434'},
 'SVM': {'place': '3',
         'name': 'Stoffel Vandoorne',
         'team': 'MCLAREN RENAULT',
         'time': '1:12.463'}}

CodePudding user response:

Iterate over the dictionary and put the count variable into "place". Notice that I converted count to a str; your example shows that you expect a string.

my_dict = {
    "SVF": {
        "place": "",
        "name": "Sebastian Vettel",
        "team": "FERRARI",
        "time": "1:04.415",
    },
    "VBM": {
        "place": "",
        "name": "Valtteri Bottas",
        "team": "MERCEDES",
        "time": "1:12.434",
    },
    "SVM": {
        "place": "",
        "name": "Stoffel Vandoorne",
        "team": "MCLAREN RENAULT",
        "time": "1:12.463",
    },
}

count = 1
for item in my_dict:
    my_dict[item]["place"] = str(count)
    count  = 1
  • Related