Rasoul Heydari
Rasoul Heydari

Reputation: 1

Combine(merge) multiple dictionaries in list respectively

I have a list called dlist that has a number of dictionaries with same keys ('Remark:').

dlist = [{'Remark:': 'S : RIH W/14" MAGNET (3TIMES) R I H W/2-1/2 R.CIR BASKET &    C'},
 {'Remark:': 'ORRING F/64 TO 64.6 P O H NO CONE, LAY DOWN F.TOOL @ RT.       R'},
 {'Remark:': 'RIH W/14" MAGNET & 8-1/2 DC TO 64 MT & CIR ON TOP OF FISH &   100'}]

I want to combine values of dictionaries respectively to have meaningful sentence (The order of the sentences is important for me). I used following code:

Combine_Dict2 = {item['Remark:'] for item in dlist if isinstance(item, dict) and 'Remark:' in item}

my output is:

Combine_Dict2 = {'ORRING F/64 TO 64.6 P O H NO CONE, LAY DOWN F.TOOL @ RT.       Ra, 'RIH W/14" MAGNET & 8-1/2 DC TO 64 MT & CIR ON TOP OF FISH &   100', 'S : RIH W/14" MAGNET (3TIMES) R I H W/2-1/2 R.CIR BASKET &    C'}

The order of the sentences is not observed. please help me.

Upvotes: 0

Views: 46

Answers (2)

azro
azro

Reputation: 54168

You are using the set-comprehension syntax with the brackets {} around your statement, which builds a set (and not a dict) which is an unordered collection.

You need a list-comprehension to keep iteration order :

result = [item['Remark:'] for item in dlist 
                          if isinstance(item, dict) and 'Remark:' in item]


['S : RIH W/14" MAGNET (3TIMES) R I H W/2-1/2 R.CIR BASKET &    C', 
 'ORRING F/64 TO 64.6 P O H NO CONE, LAY DOWN F.TOOL @ RT.       R', 
 'RIH W/14" MAGNET & 8-1/2 DC TO 64 MT & CIR ON TOP OF FISH &   100']

Upvotes: 1

rdas
rdas

Reputation: 21305

Use a list comprehension instead of a set comprehension to maintain order:

Change:

Combine_Dict2 = {item['Remark:'] for item in dlist if isinstance(item, dict) and 'Remark:' in item}

To

Combine_Dict2 = [item['Remark:'] for item in dlist if isinstance(item, dict) and 'Remark:' in item]

Using {} makes it a set comprehension, [] is a list comprehension

Upvotes: 1

Related Questions