使Python字典从退出字典

问题描述:

我提供给我的标签和数据的字典,我以下列方式使用:使Python字典从退出字典

tags_df_map = zip(tags, data) 
append_series = [series for tags,series in tags_df_map if tags['Index'] =='A'] 
append_tags = [tags['Index'] for tags, series in tags_df_map if tags['Index'] =='A'] 
series_to_append = dict(zip(append_tags,append_series)) 

有没有在Python更方便,更有效的方法来在series_to_append字典到达?在此先感谢

+0

你想只有一个键,值对的字典? – kuro

+0

[如何计算两个时间字符串之间的时间间隔]的可能重复(https://stackoverflow.com/questions/3096953/how-to-calculate-the-time-interval-between-two-time-string) – jlange

+0

@jlange,你在说什么? – kuro

您可以使用字典解析:

series_to_append = {tag[my_key]: series for tag, series in zip(tags, data) 
        if tag['Index'] == 'A'} 

请注意,我用的任意可变my_key因为我使用的访问tag生成字典理解的密钥的密钥。之前,您曾使用tag['Index']series_to_append创建密钥。这将导致series_to_append只有一个密钥('A'),因为您只使用其中tag['Index']等于'A'的值。

下面是这个字典解析中使用的例子:

data = [0,1,2,3,4,5,6] 
tags = [{'Index': 'A', 'Key': chr(x+65)} if x % 2 == 0 else {'Index': 'B', 'Key': chr(x+65)} 
     for x in range(7)] 

# the original code snippet 
tags_df_map = zip(tags, data) 
append_series = [series for tag, series in tags_df_map if tag['Index'] =='A'] 
append_tags = [tag['Index'] for tag, series in tags_df_map if tag['Index'] =='A'] 
series_to_append = dict(zip(append_tags,append_series)) 
print(series_to_append) 
>> {'A': 6} 

{tag['Index']: series for tag, series in zip(tags, data) 
        if tag['Index'] == 'A'} 
>> {'A': 6} 

{tag['Key']: series for tag, series in zip(tags, data) 
        if tag['Index'] == 'A'} 
>> {'A': 0, 'C': 2, 'E': 4, 'G': 6} 

此外,作为一个警告,因为它似乎你正在使用Python 2,使用tags为您内涵内部变量名将导致变量tags指向它在理解中分配的最后一个值(而不是它之前指向的值)。也就是说,将一个值赋给列表理解中的一个变量将被视为与列表理解之外的变量赋值相同。值得注意的是,由于如何理解范围,在Python 3中不会发生这种情况,但除非有足够的理由这样做,否则通常不要在理解中重用变量名称。