Python dict comprehension - 在创建过程中访问dict

时间:2017-12-11 23:31:24

标签: python dictionary-comprehension

我有这样的代码:

dictionary = {}

for x in dict_of_x:
  if x['duration_to_cancel'] == None or x['duration_to_cancel'] > 5:
    key = x['key']
    value = x['value']

    if key not in dictionary or value > dictionary[key]:
      dictionary[key] = value

我想让这段代码成为一种理解:

dictionary = {x['key'] : x['value'] for x in dict_of_x \
            if ( True if x['duration_to_cancel'] == None else x['duration_to_cancel'] > 5)}

如何在第一个代码框中包含第二个if语句到dict理解?

2 个答案:

答案 0 :(得分:1)

由于你所做的只是一个max,你可以使用“最大理解力”:

dict_of_x = (
    {'key':0,'value':0,'duration_to_cancel':10},
    {'key':0,'value':1,'duration_to_cancel':15},
    {'key':0,'value':2,'duration_to_cancel':1},
    {'key':1,'value':3,'duration_to_cancel':2},
    {'key':2,'value':4,'duration_to_cancel':None}
)

def yours():
    dictionary = {}
    for x in dict_of_x:
      if x['duration_to_cancel'] == None or x['duration_to_cancel'] > 5:
        key = x['key']
        value = x['value']
        if key not in dictionary or value > dictionary[key]:
          dictionary[key] = value
    return dictionary
print yours()

{0: 1, 2: 4}

def mine(): 
    dictionary = {key : max(x['value'] for x in dict_of_x if x['key'] == key) \
        for key in set(x['key'] for x in dict_of_x if x['duration_to_cancel'] == None or x['duration_to_cancel'] > 5)}
    return dictionary
print mine()

{0: 1, 2: 4}

但请注意,list / dict / set / max理解只是为了它的可读性并不一定是好事。 同样在你的实现中你只通过你的dict一次,而我的代码将循环几次,这也会降低速度:

%timeit yours()
1000000 loops, best of 3: 855 ns per loop


%timeit mine() 
100000 loops, best of 3: 2.32 µs per loop

答案 1 :(得分:0)

尝试这个,它应该工作,因为较高的值会覆盖较低的值:

dictionary = {x['key'] : x['value'] for x in sorted(dict_of_x, key=lambda x: x['value']) \
            if ( True if x['duration_to_cancel'] == None else x['duration_to_cancel'] > 5)}