1
results=[key for key, value in adictionary if str(key).startswith('target') 
    and value > 0 ]

What am I trying to do here is select all the keys if the key in dictionary that beginswith target and its value is greater than 0. But looks there's a problem with this, help me~

5 Answers 5

3
results=[key for key, value in adictionary.items() if str(key).startswith('target') 
             and value > 0 ]
Sign up to request clarification or add additional context in comments.

Comments

2

Missing items() ior iteritems() to your dict access. iteritems will not create a temp list which could be slightly faster.

results=[key for key, value in adictionary.iteritems() if str(key).startswith('target') 
             and value > 0 ]

Comments

0

You need to use the items() method to get both key and value.

 [key for key, value in adictionary.items() if str(key).startswith('target') and value > 0]

Comments

0

startswith() is slower than slicing

I would do:

results=[k for k,v in adictionary.iteritems()
         if (k[0:7]=='target')==True==(v>0)]

Comments

0

I'd use the iteritems() method of the dictionary. It returns an interator rather than generating a full list like the items() method does.

results = [key for key, value in adictionary.iteritems() if str(key).startswith('target') and value > 0]

1 Comment

@Rod yeah missed that, I'd still use the iter version though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.