如何将给定Python字典转换为以名称为键的目标键值映射格式?
Solution to Transform the Python Dictionary
First, let's break down exactly what we need to accomplish:
- Aggregate entries from both the
techandheaderslists, using each entry'snameas the key. - For duplicate names, keep the latest valid value (ignore
Nonevalues, 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
techlist: we loop through each entry. If theversionisn'tNone, 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
headerslist: we do the same mapping, but use thevaluefield instead ofversion(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
相关产品推荐
相关产品推荐

