简体   繁体   中英

How to convert a list of data in Python to a Dictionary where each item has a key

Google={}
Google["Price"]=[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]

I have a dictionary "Google" where the the key value shows 36 values for Google. Is there a way to give each entry a separate key (where 317.68 is 1, 396.05 is 2, etc)?

dict(enumerate(google_price_data, start=1))

Just use enumerate to help your key-generation task and for to loop through each item in the list.

Here you go:

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

Output:

{
    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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM