将列表转换为字典

时间:2015-08-13 13:48:47

标签: python list python-2.7 dictionary

我有这个清单:

list1 = ["a","b","c"]

我需要将它转换成这样的字典

value:{
        a:{
            timestamp: "2015-05-19T14:07:30.423765"
        }
        b:{
            timestamp: "2015-05-19T14:07:30.423765"
        }
        c:{
            timestamp: "2015-05-19T14:07:30.423765"
        }
      }

我该怎么做?

2 个答案:

答案 0 :(得分:4)

除非对问题作出任何澄清,否则应该这样做:

import pprint  # For pretty-printing the dict

your_list = ['a', 'b', 'c']

timestamp = '2015-05-19T14:07:30.423765'

your_dict = {item: {'timestamp': timestamp}) for item in your_list)

pprint.pprint(your_dict)  # Pretty-printing the dict

list1 = ["a","b","c"]
value = {k: {"timestamp":"2015-05-19T14:07:30.423765"} for k in list1}

输出:

{'a': {'timestamp': '2015-05-19T14:07:30.423765'},
 'b': {'timestamp': '2015-05-19T14:07:30.423765'},
 'c': {'timestamp': '2015-05-19T14:07:30.423765'}}

答案 1 :(得分:3)

您可以在Python 2.7+中使用字典理解,如下所示:

list1 = ["a","b","c"]
value = {k: {"timestamp":"2015-05-19T14:07:30.423765"} for k in list1}

print value

,并提供:

{'a': {'timestamp': '2015-05-19T14:07:30.423765'}, 'c': {'timestamp': '2015-05-19T14:07:30.423765'}, 'b': {'timestamp': '2015-05-19T14:07:30.423765'}}