如何将Python中的数据列表转换为每个项目都有一个键的字典

时间:2015-11-21 22:29:41

标签: python dictionary

comment

我有一个字典“Google”,其中键值显示了Google的36个值。有没有办法给每个条目一个单独的密钥(317.68是1,396.05是2,等等)?

2 个答案:

答案 0 :(得分:6)

dict(enumerate(google_price_data, start=1))

答案 1 :(得分:4)

只需使用enumerate来帮助您完成密钥生成任务,并使用for遍历列表中的每个项目。

你走了:

google_dict = dict()
google_price_data = [317.68,396.05,451.48,428.03,516.26,604.83,520.63,573.48,536.51,542.84,533.85,660.87,728.9]

for i, item in enumerate(google_price_data, start=1):
    google_dict[i] = item

print google_dict

<强>输出:

{
    1: 317.68,
    2: 396.05,
    3: 451.48,
    4: 428.03,
    5: 516.26,
    6: 604.83,
    7: 520.63,
    8: 573.48,
    9: 536.51,
    10: 542.84,
    11: 533.85,
    12: 660.87,
    13: 728.9
}