2016-08-22 48 views
0

我有一本字典,它顯示了一個人的旅程,其中空白列表意味着走路並列出內容意味着他/她所用的管道。我想找出他/她的第一次管道旅程,索引爲'2,3'。根據字典中的值查找第一組相同組的索引

specific_path_legs={0: [], 
1: [], 
2: ['Jubilee'], 
3: ['Jubilee'], 
4: [], 
5: [], 
6: ['Metropolitan'], 
7: ['Metropolitan'], 
8: ['Metropolitan'], 
9: ['Metropolitan'], 
10: [], 
11: [], 
12: [], 
13: [], 
14: ['Northern'], 
15: ['Northern'], 
16: ['Northern'], 
17: ['Northern'], 
18: ['Northern'], 
19: [], 
20: [], 
21: [], 
22: ['Jubilee'], 
23: ['Jubilee'], 
24: ['Jubilee'], 
25: [], 
26: [], 
27: []} 

我首先排除了散步部分並得到了leg_nonempty字典。

legs_nonempty={2: ['Jubilee'], 
    3: ['Jubilee'], 
6: ['Metropolitan'], 
7: ['Metropolitan'], 
8: ['Metropolitan'], 
9: ['Metropolitan'], 
14: ['Northern'], 
15: ['Northern'], 
16: ['Northern'], 
17: ['Northern'], 
18: ['Northern'], 
22: ['Jubilee'], 
23: ['Jubilee'], 
24: ['Jubilee']} 

然後我試圖

first_leg=[] 
for key,value in specific_path_legs.items(): 
    if value==legs_nonempty.itervalues().next(): 
     first_leg.append(key) 

但它返回

first_leg=[2,3, 22, 23, 24] 

我只需要[2,3]而不是[2,3,22,23,24]。有任何想法嗎?

+0

添加了答案。我假設你想爲你的字典中每個值出現最小的鍵值。 –

+0

你想要的輸出的例子真的有很大的幫助 – Andrew

+0

希望這一次,它更容易被理解。 –

回答

0
# Sort dictionary based on keys 
import collections 
specific_path_legs = collections.OrderedDict(sorted(specific_path_legs.items())) 

# Store your info in another dict 
path_legs_dict = {} 
for key, value in specific_path_legs.items(): 
    if value and value[0] not in path_legs_dict: 
     path_legs_dict[value[0]] = key 

print path_legs_dict 
# Output: {'Jubilee': 2, 'Northern': 14, 'Metropolitan': 6} 

我使用collections.OrderedDict因爲在Python默認dict對象不排序。

0

由於密鑰是增量從0開始只是去,直到你找到一個非空值:如果你也想匹配特定值

(2, ['Jubilee']) 

for i in range(len(specific_path_legs)): 
    if specific_path_legs[i]: 
     print(i, specific_path_legs[i]) 
     break 

這將使你:

for i in range(len(specific_path_legs)): 
    val = specific_path_legs[i] 
    if val and val == "Jubilee": 
     print(i ,specific_path_legs[i] 
     break