繁体   English   中英

从与一个字典中的键关联的列表中提取值以创建另一个字典

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

我创建了一个名为“ father_dict ”的字典,其键“ key ”是 1、2 和 3,并且对于这些键值中的每一个,我都有一个关联的列表。

#           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)    

从那里我寻求创建两个字典:

具有相同键但与列表相关联的第一个字典,其中仅找到“ father_dict ”列表的第一个和最后一个值。

我正在寻找的打印在屏幕上的示例:

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

同样,使用相同的键创建第二个字典,但与一个列表相关联,其中仅找到“father_dict”列表中间的值。

我正在寻找的打印在屏幕上的示例:

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

这个过程怎么做? 谢谢你。

对不起,我的英语不是我的母语。

使用字典理解切片,您可以执行以下操作:

# 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()
}

第 2 条和第 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
       }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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