-1

Convert Function:

def Convert(a):
    it = iter(a)
    res_dct = dict(zip(it, it))
    return res_dct

w=0

r=0

u={}


for q in lit:

    w=(list(q))

    r=Convert(w)


    for key, value in r.items():

        r[key] = value
   
 print(r)

Output:

{'chapter': 56} {'i': 2597} {'emma': 719} {'woodhouse': 249} {'handsome': 30} 
{'clever': 24} {'and': 4534} {'rich': 14} {'with': 1244} {'a': 3101} 
{'comfortable': 34} {'home': 112} {'happy': 116} {'disposition': 23} 
{'seemed': 139} {'to': 5202} {'unite': 3} {'some': 260} {'of': 4363} 
{'the': 5271} 

I need These outputs in a Single Dictionary

Initially The lit is a list containing the list of output

Nick
  • 138,499
  • 22
  • 57
  • 95
Asuka
  • 3
  • 2
  • Please, edit your question to properly format code block(s). – buran May 30 '22 at 07:35
  • 1
    If a key is duplicated in your list of dictionaries, do you want to overwrite, or take the sum, or what? For instance, if `{'a': 152}, {'a': 200}` are both in the list, do you want `'a': 200` or `'a': 352` in the final dictionary? – Stef May 30 '22 at 07:37
  • 1
    Merge operator (|) can be used, in Python 3.9 and above. – Zenith_1024 May 30 '22 at 07:39
  • If your list of dictionaries is `r`, then `result = {k: v for d in r for k, v in d.items()}` – Stef May 30 '22 at 07:40
  • @Stef the list doesn't contain any duplicate keys – Asuka May 30 '22 at 07:46

1 Answers1

0
lit = [{'chapter': 56},
   {'i': 2597},
   {'emma': 719},
   {'woodhouse': 249} ,
   {'handsome': 30},
   {'clever': 24} ,
   {'and': 4534},
   {'rich': 14} ,
   {'with': 1244} ,
   {'a': 3101} ,
   {'comfortable': 34},
   {'home': 112},
   {'happy': 116},
   {'disposition': 23} ,
   {'seemed': 139} ,
   {'to': 5202},
   {'unite': 3},
   {'some': 260},
   {'of': 4363} ,
   {'the': 5271}]
res = {}

for i in lit:
    for k in i:
        res[k] = i[k]

print(res)
Amir
  • 129
  • 4
  • or just `for i in lit: res.update(i)` – Stef May 30 '22 at 07:45
  • lit is a simple list it is not a list of dictionary. for instance lit=[('chapter', 56), ('i', 2597), ('emma', 719), ('woodhouse', 249), ('handsome', 30), ('clever', 24), ('and', 4534), ('rich', 14), ('with', 1244), ('a', 3101), ('comfortable', 34), ('home', 112), ('happy', 116), ('disposition', 23), ('seemed', 139), ('to', 5202), ('unite', 3), ('some', 260), ('of', 4363), ('the', 5271)] – Asuka May 30 '22 at 07:48
  • @Asuka then just `result = dict(lit)` – Stef May 30 '22 at 07:55