DaniV
DaniV

Reputation: 489

Extract values from a list associated with a key from one dictionary to create another dictionary

I have created a dictionary called ‘father_dict’, whose key ‘key’ is 1, 2 and 3 and for each of these key values I have a list associated.

#           ValueList          Key
input_data = [[ 1,     'Col',   1],  
              [ 2,     'Col',   1],   
              [ 3,     'Col',   1],   
              [ 4,     'Col',   1],   
              [ 5,     'Col',   2],
              [ 6,     'Col',   2],  
              [ 7,     'Col',   2],   
              [ 8,     'Col',   2],   
              [ 9,     'Col',   3],
              [10,     'Col',   3],
              [11,     'Col',   3],
              [12,     'Col',   3],
              [13,     'Row',   1],
              [14,     'Row',   1],
              [15,     'Row',   1],
              [16,     'Row',   2],
              [17,     'Row',   2],
              [18,     'Row',   2],
              [19,     'Row',   3],
              [20,     'Row',   3],
              [21,     'Row',   3]] 

common_character = []
father_dict = {}
for i in range(len(input_data)): 
    if input_data[i][1] == 'Col':
        common_character.append(input_data[i][2])
print(common_character)

flat_list = list(set(common_character))
print(flat_list)

for j in flat_list:
    father_dict[j] = []
print(father_dict)

for i in range(len(input_data)):
    if input_data[i][1] == 'Col':
        key = input_data[i][2]
        father_dict[key].append(input_data[i][0])
print(father_dict)    

From there I seek to create two dictionaries:

A first dictionary with the same keys but that is associated to a list where only the first and last value of the list of ‘father_dict’ are found.

Example of what I am looking for printed on screen:

{1: [1, 4], 2: [5, 8], 3: [9, 12]}

Likewise, create a second dictionary with the same keys but that are associated with a list where only the values in the middle of the ‘father_dict’ list are found.

Example of what I am looking for printed on screen:

{1: [2, 3], 2: [6, 7], 3: [10, 11]}

How could this process be done? Thank you.

Excuse my English, it is not my native language.

Upvotes: 0

Views: 66

Answers (2)

0buz
0buz

Reputation: 3503

Using dictionary comprehension and slicing, you can do something like:

# first and values
result1={
    k:[v[0],v[-1]] for k,v in father_dict.items()
}

# middle values
result2={
    k:[v[1:-1]] for k,v in father_dict.items()
}

Upvotes: 2

Old Winterton
Old Winterton

Reputation: 120

dicts 2 and 2a:

#{ Key: [ dict[key][value at first position], dict[key][value at last position] ] } #do for each entry in source dict
d2a = {i:[ father_dict[i][0],father_dict[i][-1] ]
       for i in father_dict
       }

#{ Key: dict[key][positions 1 to just before last position] } #for each entry in source dict
d2b = {i: father_dict[i][1:-1]
       for i in father_dict
       }

Upvotes: 1

Related Questions