Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: select dictionary items by key

I have this dictionary:

a = { 
    'car1': ('high cp', 'low fd', 'safe'),
    'car2': ('med cp', 'med fd', 'safe'), 
    'car3': ('low cp', 'high fd', 'safe'), 
    'taxi1': ('high cp', 'low fd', 'safe', 'med wt'), 
    'taxi2': ('high cp', 'low fd', 'safe', 'high wt'), 
    'taxi3': ('high cp', 'low fd', 'safe', 'high wt')
}

From the above dictionary, I want to create a new dictionary that consists only 'car%s'

I'm using this code snippet (from another question)

b = {}
for key in a:
    if key == 'car%s'% (range (4)):
        print (" %s : %s" % (key, a[key]))
print(b)

It returns {}

I expect to get:

a = { 
    'car1': ('high cp', 'low fd', 'safe'),
    'car2': ('med cp', 'med fd', 'safe'), 
    'car3': ('low cp', 'high fd', 'safe'), 
}

What am I missing here?

like image 637
dya Avatar asked Sep 12 '25 06:09

dya


1 Answers

You're checking the prefix the wrong way and you're not storing the result. You could use str.startswith and dict comprehension to generate the result:

>>> a = { 
... 'car1': ('high cp', 'low fd', 'safe'),
... 'car2': ('med cp', 'med fd', 'safe'), 
... 'car3': ('low cp', 'high fd', 'safe'), 
... 'taxi1': ('high cp', 'low fd', 'safe', 'med wt'), 
... 'taxi2': ('high cp', 'low fd', 'safe', 'high wt'), 
... 'taxi3': ('high cp', 'low fd', 'safe', 'high wt')
... }
>>> res = {k: v for k, v in a.items() if k.startswith('car')}
>>> res
{'car2': ('med cp', 'med fd', 'safe'), 'car3': ('low cp', 'high fd', 'safe'), 'car1': ('high cp', 'low fd', 'safe')}

Instead of inserting a number to the format string your current check inserts the range object there which probably isn't the result you expect:

>>> 'car%s'% (range (4))
'carrange(0, 4)'
like image 128
niemmi Avatar answered Sep 14 '25 20:09

niemmi