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

如何将给定Python字典转换为以名称为键的目标键值映射格式?

Solution to Transform the Python Dictionary

First, let's break down exactly what we need to accomplish:

  • Aggregate entries from both the tech and headers lists, using each entry's name as the key.
  • For duplicate names, keep the latest valid value (ignore None values, and overwrite with later entries if they have a valid value).
  • Wrap the final aggregated data under the domain key http://mychoicedomain.com.

Here's a clean, straightforward implementation in Python:

# Original input dictionary
xx = {
    'tech': [
        {'name': 'Bootstrap', 'version': None},
        {'name': 'jQuery', 'version': '3.3.1'},
        {'name': 'Bootstrap', 'version': '3.3.7'}
    ],
    'headers': [
        {'value': 'WSGIServer/0.2 CPython/3.5.2', 'name': 'Server'}
    ]
}

# Initialize our result structure
result = {'http://mychoicedomain.com': {}}
target_dict = result['http://mychoicedomain.com']

# Process tech entries: skip None versions, keep latest valid value
for item in xx['tech']:
    name = item['name']
    version = item['version']
    if version is not None:
        target_dict[name] = version

# Process headers entries: map name to its value
for item in xx['headers']:
    name = item['name']
    value = item['value']
    target_dict[name] = value

# Verify the result
print(result)

How this works:

  • We start by setting up the base structure of our desired output.
  • For the tech list: we loop through each entry. If the version isn't None, we update our target dictionary—later valid entries for the same name will automatically overwrite earlier ones, giving us the latest valid value.
  • For the headers list: we do the same mapping, but use the value field instead of version (since that's where the relevant data lives here).

Output:

{'http://mychoicedomain.com': {'Bootstrap': '3.3.7', 'jQuery': '3.3.1', 'Server': 'WSGIServer/0.2 CPython/3.5.2'}}

This approach is efficient, easy to read, and checks all your boxes: handling None values, prioritizing the latest valid entry for duplicates, and matching the exact output format you need.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:44:31