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?
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)'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With