You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Lambda函数优化Python字典列表的自定义键顺序排序实现?

Reorder Dictionaries in a List by Specified Key Order with Lambda in Python

Problem Statement

I have a list of dictionaries:

list_1 = [{"three":3, "two":2, "four":4, "six":6, "five":5, "seven":7, "one":1}, {"six":6, "three":3, "seven":7, "one":1, "two":2, "four":4, "five":5}]

I want to reorder the keys of each dictionary to match this specified order:

keys_list = ["one", "two", "three", "four", "five", "six", "seven"]

Expected result:

result_list = [{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7}, {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7}]

I've implemented this with a loop:

result_list=[]
result_dict={}
for i in list_1:
    for idx, j in enumerate(keys_list):
        result_dict[keys_list[idx]] = i[j]
    result_list.append(result_dict)
print(result_list)

Can I optimize this using a Lambda function?


Solution

Absolutely! First, let's fix a subtle bug in your original code: you defined result_dict outside the loop, so every iteration modifies the same dictionary object and adds it to result_list. This means all entries in your final list will point to that single dictionary, resulting in duplicate entries of the last processed item.

Now, here are two optimized approaches, including a lambda-based solution:

This is the most concise and readable way, no lambda required but still far more efficient than nested loops:

list_1 = [{"three":3, "two":2, "four":4, "six":6, "five":5, "seven":7, "one":1}, {"six":6, "three":3, "seven":7, "one":1, "two":2, "four":4, "five":5}]
keys_list = ["one", "two", "three", "four", "five", "six", "seven"]

result_list = [{key: d[key] for key in keys_list} for d in list_1]
print(result_list)

This creates a new dictionary for each item in list_1, iterating through your keys_list to build the ordered key-value pairs.

2. Lambda + map() Function

If you specifically want to use a lambda, you can pair it with map() to apply the reordering logic to every dictionary in the list:

result_list = list(map(lambda d: {key: d[key] for key in keys_list}, list_1))

Here, the lambda function takes each dictionary d and returns a new ordered dictionary using the same dictionary comprehension as above. We wrap map() with list() to convert the iterator into a list of dictionaries.

Both approaches will produce your desired result_list correctly, without the duplicate reference bug from your original code.


内容的提问来源于stack exchange,提问作者mahen1812

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 17:37:50