我有一个如下列表:
l = [{'Value': 'value1', 'Key': 'key1'}, {'Value': 'value2', 'Key': 'key2'}, {'Value': 'value3', 'Key': 'key3'}]
我想要一个输出列表如下:
lst = [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]
我的代码如下:
lst = []
for item in l:
key = item["Key"]
value = item["Value"]
dict = {}
dict[key] = value
lst.append(dict)
是否可以在列表推导的单行中执行相同操作?
答案 0 :(得分:8)
l = [{'Value': 'value1', 'Key': 'key1'}, {'Value': 'value2', 'Key': 'key2'}, {'Value': 'value3', 'Key': 'key3'}]
>>> [{item['Key']: item['Value']} for item in l]
[{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]