【问题标题】:Python Dictionary how to substitute the list of values to make dictionaryPython Dictionary如何替换值列表以制作字典
【发布时间】:2019-03-30 02:02:04
【问题描述】:

我有以下字典:

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'}]}

我想把上面的字典转换成下面的格式。其中name 应充当字典的KEYversionvalue 应充当Value

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

【问题讨论】:

  • 你的尝试在哪里?

标签: python python-3.x python-2.7 dictionary


【解决方案1】:
xx = {'http://mychoicedomain.com':{d['name']:d['version'] for d in xx['tech']}}

【讨论】:

  • 如果字典列表中有多个具有相同name的字典,此代码将只保留最后一个。
  • 你错过了headers
【解决方案2】:

首先提取值,然后将它们组合成值就可以了。

x1 = {d['name']:d['version'] for d in xx['tech']}
x2  = {d['name']:d['value'] for d in xx['headers']}
xx = {}
xx['http://mychoicedomain.com'] = dict(**x1,**x2)

【讨论】:

    猜你喜欢
    • 2019-02-23
    • 2010-11-07
    • 2023-03-10
    • 2020-07-11
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    相关资源
    最近更新 更多