Home > front end >  convert list dict into dict
convert list dict into dict

Time:04-17

I am trying to convert list dictionary into dictionary. I have tried many method but it is showing different errors, I am new in python.

def function_name(request):
    data = [{"key":"111","value":"222"},{"key":"3333","value":"4"444}]

What have I tried

1). I have tried using reduce like :-

res = reduce(lambda aggr, new: aggr.update(new) or aggr, data, {})

but it showed

ValueError: dictionary update sequence element #0 has length 1; 2 is required

2). Then I tried extracting separately key,value in for loop like :-

    newdict={}
    for k,v in [(key,d[key]) for d in data for key in d]:
      if k not in newdict: newdict[k]=[v]
      else: newdict[k].append(v)

but it showed

TypeError: string indices must be integers

3). Then I tried like :-

pr = dict((key,d[key]) for d in data for key in d)

but it showed

TypeError: string indices must be integers

What I am trying to do

I am trying to convert this below list dict into dict like

{"1111":"2222", "3333":"4444"}

I have tried many times but it is still showing errors. Any help would be much Appreciated, Thank You in Advance

CodePudding user response:

you can try this.

old_list = [{"key":"111","value":"222"},{"key":"3333","value":"4444"}]
new_dict = {}

for dict_ in old_list:
    new_dict[dict_['key']]=dict_['value']

print(new_dict)

CodePudding user response:

data = [{"key":"111", "value":"222"},{"key":"3333", "value":"4444"}]
result = dict(item.values() for item in data)
print(result)

output

{'111': '222', '3333': '4444'}

Note, this assumes python 3.7 where dicts preserve order of insertion

  • Related