python3使用zip和map制作一个dict列表

时间:2017-08-24 08:44:20

标签: python

我正在努力制作一个dict列表,如(A => B):

A:

{
    "macro": ["{$URL}","{$USERNAME}","{$PASSWORD}"],
    "value": ['https://1.1.1.1/sdk',"vmuser","vm@2980"]
}

B:

[
        {
            "macro": "{$PASSWORD}",
            "value": "vm@2980"
        },
        {
            "macro": "{$USERNAME}",
            "value": "vmuser"
        },
        {
            "macro": "{$URL}",
            "value": 'https://' + hostip + '/sdk'
        },
]

我的解决方案如下所示,但是python2正如我所说,python3不是。

Python 2.7.9

>>> cc=dict(macro=["{$URL}","{$USERNAME}","{$PASSWORD}"],value=['https://' + "123" + '/sdk',"vmuser","vm@2980"])
>>> ret=[]
>>> for k,v in cc.items():
...   ret.append(map(lambda x:{k: x},v))
... 
>>> ret
[[{'macro': '{$URL}'}, {'macro': '{$USERNAME}'}, {'macro': '{$PASSWORD}'}], [{'value': 'https://123/sdk'}, {'value': 'vmuser'}, {'value': 'vm@2980'}]]
>>> ret[0]
[{'macro': '{$URL}'}, {'macro': '{$USERNAME}'}, {'macro': '{$PASSWORD}'}]
>>> zip(*ret)
[({'macro': '{$URL}'}, {'value': 'https://123/sdk'}), ({'macro': '{$USERNAME}'}, {'value': 'vmuser'}), ({'macro': '{$PASSWORD}'}, {'value': 'vm@2980'})]

Python 3.4.2

>>> cc=dict(macro=["{$URL}","{$USERNAME}","{$PASSWORD}"],value=['https://' + "123" + '/sdk',"vmuser","vm@2980"])
>>> ret=[]
>>> for k,v in cc.items():
...   ret.append(map(lambda x:{k: x},v))
... 
>>> ret
[<map object at 0x7faed946c1d0>, <map object at 0x7faed946c208>]
>>> ret=[]
>>> for k,v in cc.items():
...   ret.append(map(lambda x:{k: x},v))
... 
>>> ret
[<map object at 0x7faed946c390>, <map object at 0x7faed946c400>]
>>> c=zip(*ret)
>>> next(c)
({'macro': 'https://123/sdk'}, {'macro': '{$URL}'})

我想知道为什么python3键是宏的?还有更好的方法吗?

1 个答案:

答案 0 :(得分:4)

在Python 3中map()返回迭代器,而在Python 2中它返回一个列表。要在Python 3中获取相同的列表,您需要将map()包装在list()中。

也就是说,要获得所需格式的列表,您可以将zip()与列表理解结合使用:

B = [{"macro": m, "value": v} for m, v in zip(A["macro"], A["value"])]

演示:

>>> A = {
...     "macro": ["{$URL}", "{$USERNAME}", "{$PASSWORD}"],
...     "value": ["https://1.1.1.1/sdk", "vmuser", "vm@2980"]
... }
>>> [{"macro": m, "value": v} for m, v in zip(A["macro"], A["value"])]
[{'macro': '{$URL}', 'value': 'https://1.1.1.1/sdk'}, {'macro': '{$USERNAME}', 'value': 'vmuser'}, {'macro': '{$PASSWORD}', 'value': 'vm@2980'}]