简体   繁体   中英

How to convert 2 list in a python dict?

When I zip 2 list to create a python dict, only ak,v is returnd, but my 2 lists have length = 5.

my lists look like this:

Date_List = ['2019-11-04', '2019-11-04', '2019-11-04', '2019-11-04', '2019-11-04']
Gains_List = [0.0, -0.16873767942313656, 0.7362161773647236, -0.13807995856330857, 0.2844974266425382]

The length of both is equal, so, I try to create a dict using dict comprehension:

accumulated = {k: v for k, v in zip(new_data_list, ganhos)}

But, when I print accumulated the return is only one values like:

{'2019-11-04': 0.2844974266425382}

Another thing that happens is that da date '2019-11-04' have values 0.00 but when I zip, the dict get the last value in Gains_List and put in like first value in the dict.

The result should be look like this:

{2019-11-04: 0.000000, 2019-11-05: -0.168738, 2019-11-06: 0.736216, 2019-11-07: -0.138080, 2019-11-08: 0.284497}

The reason behind that is that while you are iterating the result of the zip command you are updating the resulting dictionary instead of extending it.

The zip command results in a tuple array:

[('2019-11-04', 0.0), ('2019-11-04', -0.16873767942313656), ...]

Then you want to create a dictionary out of each tuple (key, value). But the key is always the same thus Python is updating the existing key instead of extending the dictionary as each key has to be unique.

Your code is actually good! It does precisely what you expect it to do. However, as you sure know, Python's dictionaries have the format of {key: value} , where every key is unique . This is where it's gone wrong. The values in Date_List are all '2019-11-04' , and since you're using this as the key for the dictionary, the comprehension keeps iteratively changing the value under '2019-11-04' key from 0.0 (first element of Gains_List ) to 0.2844974266425382 (last element of Gains_List ).

If you insist on having the keys all the same, you could turn it into an array of tuples, or a dictionary with the key and all the values from Gains_List as the value.

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