简体   繁体   中英

Mapping a dictionary key and its corresponding values from a list?

I've managed to read in a .txt file and read in each line as a different element of a list; pretty easy. Next I stripped all the non-numerical characters from each element (leaving just 0-9 and '.'), also pretty easily done.

However, then I'm left with a list with 90 total elements. Starting from element 0, I want every 5th element to be the key to my dictionary (0, 5, 10, 15, etc). Then I want the 4 value in between to correspond to the values of the previous key (as a list length 4).

For example: my_list[0] is the key with corresponding values my_list[1:5] my_list[5] is the key with corresponding values my_list[6:10] etc, etc

I've managed to take every 5th element out and make it it's own list; just holding the keys. And I've even managed to create another list which holds all the in between values as seperate lists of length 4.

I've tried:

my_dict = dict()

for i in my_keys:
    my_dict[i] = [x for x in every_four]

AND

my_dict = dict()

for i in my_keys:
    for x in every_four:
        my_dict[i] = x

The first one gives me the correct keys but each value is just a the whole every_four list, not just every element. The second one gives me the correct keys but each value is just the first element of the every_four list, it's not iterating through.

Can someone help me get it working this way? And is there any easier way I can do this from the original array? Just set every 5th element to a key and the four elements in between as the corresponding values for that key?

If you want every fifth element as key of your dictionary and list of next consecutive four elements as values, then you can try dictionary comprehension.

my_dict = {my_list[i] : my_list[i+1 : i+5] for i in range(0, len(my_list), 5)}

For sample input -

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

output will be -

{0: [1, 2, 3, 4], 5: [6, 7, 8, 9]}

But this code will generate an empty list as value if for a key no next element is present.

Input -

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Output -

{0: [1, 2, 3, 4], 10: [], 5: [6, 7, 8, 9]}

As for your code, assuming you get every_four and my_keys correct, there are some problems. In your second attempt, you are looping over every element in the my_keys list and adding that as key of the dictionary. And in the inner loop you are adding x as the value of the dictionary. So, for every iteration in your inner loop, the value for key i is getting overwritten. What you could have done is -

my_dict = dict()

for i in my_keys:
    for x in every_four:
        my_dict.setdefault(i, []).append(x)

For first attempt, I really need to see how you get my_keys and every_four to point out the error.

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