简体   繁体   English

Python:按键选择字典项

[英]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' 从以上字典中,我想创建一个仅包含“ 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? 我在这里想念什么?

If you want to add keys which contain word car in it, then it will work: 如果要添加其中包含单词car键,则它将起作用:

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')
}

b = {}
for key in a:
    if 'car' in key:
        print (key, a[key])
        b[key] = a[key]
print(b)

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: 您可以使用str.startswith和dict comprehension生成结果:

>>> 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: 当前的检查不是在格式字符串中插入数字,而是在其中插入range对象,这可能不是您期望的结果:

>>> 'car%s'% (range (4))
'carrange(0, 4)'

You never do anything with the keys you validate but print them. 您永远不会对已验证的密钥进行任何操作,而是print它们。 You need to add them to your new dictionary: 您需要将它们添加到新词典中:

b ={}
for key, val in a.items(): # .iteritems() for Python 2.x users
   if key == 'car%s' % (range (4)):
       b[key] = val
print(b)

Your code is would still be broken however. 您的代码仍然会被破坏。 You need to make some changes: 您需要进行一些更改:

  • The only prefix you need to check is "car" . 您需要检查的唯一前缀是"car" Forget trying to match the whole string. 忘记尝试匹配整个字符串。
  • This entire for loop could be made into a very simple dictionary comprehension: 整个for循环可以做成一个非常简单的字典理解:

     >>> 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') ... } >>> {k: v for k, v in a.items() if k[0:3] == 'car'} {'car2': ('med cp', 'med fd', 'safe'), 'car3': ('low cp', 'high fd', 'safe'), 'car1': ('high cp', 'low fd', 'safe')} >>> 

This works: 这有效:

new_dict = {}

for k in a.keys():
    if 'car' in k:
        new_dict[k] = a[k]

result: 结果:

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

what do you expect from range(4)? 您对range(4)有什么期望? It returns [0, 1, 2, 3] 返回[0, 1, 2, 3]

b = {}
for key in range(4):
    new_key = "car%s" % key # generate new_key
    item = a.get(new_key)
    if item is not None:
        b[new_key] = item
print (b)

OR you want to get items only starts with car , read this link https://docs.python.org/3/library/stdtypes.html#str.startswith 或者您只想让商品以car开头,请阅读此链接https://docs.python.org/3/library/stdtypes.html#str.startswith

b = {}
for key, value in a.items():
    if key.startswith("car"):
        b[key] = a[key]
print (b)

output 输出

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM