Python, How to add Key+Number to Dict if key already exists

Beardlongo :

I am a beginner, so this might be silly, but i cant figure out how to add a new Key to a Dictionary, if the Key is already in it, Without overwriting it.

Currently i have:

l1 = ["name = Carl",
"type = Fighterplane",
"name = wing fusulage",
"name = landing gear"]

and using my Code i get:

for i in l1:
    if "=" in i:
        i = i.split("=")
        key = i[0].strip()
        value = i[-1].strip()
        d1[key] = value
print(d1)

>>> d = {'name': 'landing gear', 
         'type': 'Fighterplane'}

But i would like to get:

d = {"name":"Carl",
    "type":"Fighterplane",
    "name-1":"wing fusulage",
    "name-2":"landing gear"}

I have been trying some stuff, and ran a while loop while the key is already in the Dict, but i got either only "name-1" and overwrite "name-1" or "name-1-2-3-4 ...". This should be that hard, since i can do this by creating new Windows folder and get "new Folder (2)", but i cant wrap my head around it and searches only gave my basic stuff.

kederrac :

you can use a dictionary comprehension:

r = {}
for l in l1:
    k, v = map(str.strip, l.split('='))
    r.setdefault(k, []).append(v)

result = {k if i==0 else f'{k}-{i}': e  for k, v in r.items() for i, e in enumerate(v)}

output:

{'name': 'Carl',
 'name-1': 'wing fusulage',
 'name-2': 'landing gear',
 'type': 'Fighterplane'}

if the insertion order in the dict is important:

r = {}
count = {}
for l in l1:
    k, v = map(str.strip, l.split('='))
    if k not in count:
        count[k] = 1
        r[k] = v
    else:
        r[f'{k}-{count[k]}'] = v
        count[k] += 1

r

output:

{'name': 'Carl',
 'type': 'Fighterplane',
 'name-1': 'wing fusulage',
 'name-2': 'landing gear'}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=387203&siteId=1