![](/img/trans.png)
[英]How do I get a specific value from a key in a dictionary with multiple values per key?
[英]within a dictionary, how do I remove a value from a key with multiple values? Python
from collections import OrderedDict
def main():
dictionary = OrderedDict()
dictionary["one"] = ["hello", "blowing"]
dictionary["two"] = ["frying", "goodbye"]
for key in dictionary:
print key, dictionary[key]
user_input = raw_input("REMOVE BUILDINGS ENDING WITH ING? Y/N")
if user_input == ("y"):
print ""
for key in dictionary:
for x in dictionary[key]:
if ("ING") in x or ("ing") in x:
del dictionary[key][x]
print ""
for key in dictionary:
print key, dictionary[key]
main()
我正在尝试从字典中的所有键中删除其中带有“ ing”的任何项目,例如,从键“ one”中删除“ blowing”,从键“ two”中删除“ frying”。
产生的字典将来自此:
one ['hello', 'blowing'], two ['frying', 'goodbye']
对此:
one ['hello'], two ['goodbye']
字典理解。
return {x : [i for i in dictionary[x] if not i.lower().endswith('ing')] for x in dictionary}
编辑以将“ ing”结尾的值替换为“ removed”
return {x : [i if not i.lower().endswith('ing') else 'removed' for i in dictionary[x]] for x in dictionary}
您可以通过使用dict理解以不可变的方式(即,不改变原始dict)来做到这一点:
>>> d = {'one': ['hello', 'blowing'], 'two': ['frying', 'goodbye']}
>>> {k: [w for w in v if not w.lower().endswith('ing')] for k, v in d.items()}
{'one': ['hello'], 'two': ['goodbye']}
尝试这个:
>>> collections.OrderedDict({key:filter(lambda x:not x.endswith('ing'), value) for key,value in dictionary.items()})
OrderedDict([('two', ['goodbye']), ('one', ['hello'])])
{key: [ele for ele in val if not ele.lower().endswith('ing')] for key, val in d.items()}
说明:
从右边开始
d
是字典,它存储<key, [val]>
对于d
每个key, val
我们执行以下操作,
[ele for ele in val if not ele.lower().endswith('ing')]
表示对于list( val
)中的每个元素( ele
),我们执行以下操作:
if not
),则得到ele
然后,您只需打印{ key: [ele1, ele2, ..] , .. }
。
您试图删除的字符串索引不是int位置参考。 这是修改后的代码:
from collections import OrderedDict
def main():
dictionary = OrderedDict()
dictionary["one"] = ["hello", "blowing"]
dictionary["two"] = ["frying", "goodbye"]
for key in dictionary:
print key, dictionary[key]
user_input = raw_input("REMOVE BUILDINGS ENDING WITH ING? Y/N")
if user_input == ("y"):
print ""
for key,value in dictionary.iteritems():
for i,x in enumerate(value):
if ("ING") in x or ("ing") in x:
del dictionary[key][i]
print ""
for key in dictionary:
print key, dictionary[key]
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.