[英]Ordered changing of dictionary keys (Python)
I know it is possible to change the keys in a dictionary. 我知道可以更改字典中的键。 But is it possible to change all the keys using a defined pattern? 但是是否可以使用定义的模式更改所有键? In this case I have a dictionary that contain: 在这种情况下,我有一个包含以下内容的字典:
{'>Apple': 'Orange', '>Grape': 'Hopz'}
Question: All key's contain a '>' + string. 问题:所有键都包含“>” +字符串。 Can I remove these '>' and update? 我可以删除这些“>”并进行更新吗? Or update without '>'? 还是没有'>'进行更新?
Little background: In my script I try to compare one dictionaries values to this examples keys which results in an error. 背景知识:在我的脚本中,我尝试将一个字典值与此示例键进行比较,这将导致错误。 I assume this is due to the '>' because v =! 我认为这是由于'>',因为v =! k if k = '>foo' and v = 'foo' 如果k ='> foo'且v ='foo'则为k
If any of you are scientist this '>' is a result of a fasta parser. 如果您中的任何一位是科学家,则此'>'是fasta解析器的结果。 Which I could probably just change the script to not write the '>' at the start of a line (I haven't tried this..yet). 我可能只是将脚本更改为在一行的开头不写“>”(我还没有尝试过。。
It's easy enough with a dict comprehension: dict理解很简单:
updateddict = {k.lstrip('>'): v for k, v in yourdict.iteritems()}
for Python 2.7. 适用于Python 2.7。 For Python 3, use yourdict.items()
instead. 对于Python 3,请改用yourdict.items()
。
For Python 2.6 and earlier, where there is no dict comprehension syntax yet, use: 对于Python 2.6和更早版本(尚无dict理解语法),请使用:
updateddict = dict((k.lstrip('>'), v) for k, v in yourdict.iteritems())
str.lstrip()
is a quick and concise method to remove any >
characters from the start of a key. str.lstrip()
是一种快速简洁的方法,可从键的开头删除任何>
字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.