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

Swift3:如何基于displayOrder键对API返回的嵌套字典排序

Sorting Nested Dictionary by displayOrder to Match Desired Sequence

Got it, let's tackle this sorting problem for your nested dictionary. Your goal is to reorder the entries from [SALE, OFFER, DISCOUNT, SOLD] to [SALE, SOLD, OFFER, DISCOUNT], which aligns perfectly with sorting by the displayOrder value in ascending order (1 → 2 → 3 → 4). Here's how to implement this in two common languages:

Python Solution

First, let's define your original data properly as a Python dictionary:

original_data = {
    "SALE": {"displayOrder": 1, "segId": 2, "chg": 2},
    "OFFER": {"displayOrder": 3, "segId": 4, "chg": 2},
    "DISCOUNT": {"displayOrder": 4, "segId": 1, "chg": 1},
    "SOLD": {"displayOrder": 2, "segId": 2, "chg": 1}
}

Then, use the sorted() function to order the items by the displayOrder value, then convert back to a dictionary (Python 3.7+ preserves insertion order):

# Sort items by the displayOrder key in each nested dict
sorted_items = sorted(original_data.items(), key=lambda item: item[1]["displayOrder"])

# Convert sorted items back to a dictionary
sorted_data = dict(sorted_items)

# Output the result
print(sorted_data)

This will give you your desired order:

{
    "SALE": {"displayOrder": 1, "segId": 2, "chg": 2},
    "SOLD": {"displayOrder": 2, "segId": 2, "chg": 1},
    "OFFER": {"displayOrder": 3, "segId": 4, "chg": 2},
    "DISCOUNT": {"displayOrder": 4, "segId": 1, "chg": 1}
}

JavaScript Solution

If you're working with JavaScript, here's how to achieve the same result:

const originalData = {
    "SALE": { displayOrder: 1, segId: 2, chg: 2 },
    "OFFER": { displayOrder: 3, segId: 4, chg: 2 },
    "DISCOUNT": { displayOrder: 4, segId: 1, chg: 1 },
    "SOLD": { displayOrder: 2, segId: 2, chg: 1 }
};

// Convert object to entries, sort by displayOrder, then convert back to object
const sortedData = Object.fromEntries(
    Object.entries(originalData).sort((a, b) => a[1].displayOrder - b[1].displayOrder)
);

console.log(sortedData);

Key Idea

The core approach across languages is:

  • Convert the dictionary/object into a list of key-value pairs
  • Sort this list using the displayOrder value from each nested entry as the sorting key
  • Convert the sorted list back into a dictionary/object (making sure your language preserves insertion order for this step)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:58:50