简体   繁体   中英

How to change the Key and Value in a list of dict in python?

Looking for an efficient python code to achieve the below functionality.

input_dir =[{'NAME': 'ABC', 'VALUE': 'USA'}, {'NAME': 'PQR', 'VALUE': 'EU'}]
expected_output= {'ABC': 'USA', 'PQR': 'EU'}

and i am using the below code.

out_key = ''
out_value = ''
output_dictionary = {}
for index, item in enumerate(input_dir):
   for key in item:
          if key == 'NAME':
                 out_key = item[key]
          elif key == 'VALUE':
                 out_value = item[key]
   output_dictionary[out_key] = out_value
print(output_dictionary)

Is there any efficient way to do this? Any suggestions!

Just a one liner actually. Do a dictionary comprehension as follows.

In [209]: {d["NAME"]:d["VALUE"] for d in input_dir}
Out[209]: {'ABC': 'USA', 'PQR': 'EU'}

I haven't yet tested the following code on a computer, but you should be able reduce your code with a lambda function and iterating through the input dictionary:

 f = lambda x: (x['NAME'], x['VALUE'])
output_dictionary = dict(f(i) for i in input_dir)

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM