2

I have input data like below

[{'s1': 'INT', 's2': 'INT'}, {'s1': 'TINYINT', 's2': 'TINYINT'}, {'s1': 'SMALLINT', 's2': 'SMALLINT'}, {'s1': 'BIGINT', 's2': 'BIGINT'}, {'s1': 'BIT', 's2': 'VARCHAR(10)'}, {'s1': 'FLOAT', 's2': 'FLOAT'}]

and want output as below.

{'INT':'INT', 'TINYINT': 'TINYINT', 'SMALLINT': 'SMALLINT', 'BIGINT': 'BIGINT', 'BIT': 'VARCHAR(10)', 'FLOAT': 'FLOAT'}

I have gone through the below SO question but didn't have no luck.

How do I merge a list of dicts into a single dict?

Any suggestions please.

data_addict
  • 816
  • 3
  • 15
  • 32

4 Answers4

4

You can use a simple dictionary comprehension:

a = [{'s1': 'INT', 's2': 'INT'}, 
     {'s1': 'TINYINT', 's2': 'TINYINT'}, 
     {'s1': 'SMALLINT', 's2': 'SMALLINT'}, 
     {'s1': 'BIGINT', 's2': 'BIGINT'}, 
     {'s1': 'BIT', 's2': 'VARCHAR(10)'}, 
     {'s1': 'FLOAT', 's2': 'FLOAT'}]

d = {x['s1']: x['s2'] for x in a}
print(d)

Output:

{'BIGINT': 'BIGINT',
 'BIT': 'VARCHAR(10)',
 'FLOAT': 'FLOAT',
 'INT': 'INT',
 'SMALLINT': 'SMALLINT',
 'TINYINT': 'TINYINT'}
Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
4

This is one approach.

s = [{'s1': 'INT', 's2': 'INT'}, {'s1': 'TINYINT', 's2': 'TINYINT'}, {'s1': 'SMALLINT', 's2': 'SMALLINT'}, {'s1': 'BIGINT', 's2': 'BIGINT'}, {'s1': 'BIT', 's2': 'VARCHAR(10)'}, {'s1': 'FLOAT', 's2': 'FLOAT'}]
print(dict((i["s1"], i["s2"]) for i in s))

Output:

{'SMALLINT': 'SMALLINT', 'INT': 'INT', 'FLOAT': 'FLOAT', 'TINYINT': 'TINYINT', 'BIGINT': 'BIGINT', 'BIT': 'VARCHAR(10)'}
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

This is a simple python code and it gives the same output which is asked in the question.

dict_list = [{'s1': 'INT', 's2': 'INT'}, {'s1': 'TINYINT', 's2': 'TINYINT'}, {'s1': 'SMALLINT', 's2': 'SMALLINT'}, {'s1': 'BIGINT', 's2': 'BIGINT'}, {'s1': 'BIT', 's2': 'VARCHAR(10)'}, {'s1': 'FLOAT', 's2': 'FLOAT'}]
new_dict = {}
for dl in dict_list:
    new_dict[dl['s1']] = dl['s2']

print(new_dict)

The below output we get by running this code snippet

{'SMALLINT': 'SMALLINT', 'INT': 'INT', 'FLOAT': 'FLOAT', 'TINYINT': 'TINYINT', 'BIGINT': 'BIGINT', 'BIT': 'VARCHAR(10)'}
Vishal Nagda
  • 1,165
  • 15
  • 20
-1

though keyur Pordars answer will work out, but to make it more generic using dict comprehension using python 3.6.

b = {list(k.values())[0]:list(k.values())[1] for k in a} 

# k.values() return the **view** of the values (not a list in python 3) of

# each dict item in the list and then we wrap it into a list a and index it.

print(b) # print the output

# OUTPUT {'INT': 'INT', 'TINYINT': 'TINYINT', 'SMALLINT': 'SMALLINT', 'BIGINT': 'BIGINT', 'BIT': 'VARCHAR(10)', 'FLOAT': 'FLOAT'}
P.hunter
  • 1,345
  • 2
  • 21
  • 45