![](/img/trans.png)
[英]How to append a dictionary to another dictionary string key in Python3?
[英]How to append characters to a string being used as a python dictionary key (when there are multiple entries related to that string)?
我從HMMER生成的輸出文件中提取序列坐標(找到DNA序列,在基因組裝配文件中匹配查詢)。
我創建了一個python字典,其中鍵是源序列名稱(字符串),值是包含目標序列的起始和結束坐標的列表。 然而,HMMER經常在單個源序列(重疊群/染色體)上發現多個匹配。
這意味着當我添加到字典中時,如果我遇到重疊群上的多個匹配項,則每個匹配項都會被覆蓋。
例如,HMMER發現以下匹配:
名稱開始結束
4415 16723 17556
127 1290 1145
1263 34900 37834
4415 2073 3899
4415 4580 6004
但這會產生以下字典(我希望每個匹配單獨輸入):
{'127':['1290','1145'],'1263':['34900','37834'],'4415':['4580','6004']}
如何在密鑰上附加一個字母,以便后續匹配是唯一的,不會覆蓋以前的匹配,即4415,4415a,4415b等等?
matches = {}
for each line of HMMER file:
split the line
make a list of fields 4 & 5 (the coordinates)
# at this stage I need a way of checking whether the key (sequenceName)
# is already in the dictionary (easy), and if it is, appending a letter
# to sequenceName to make it unique
matches[sequenceName] = list
在相同的情況下,創建不同的鍵不是一種正確的方法,而是可以使用列表作為值並保留其中的坐標,以用於重復鍵。 您可以使用collections.defaultdict()
實現此目標:
>>> coords = [['4415', '16723', '17556'], ['127', '1290', '1145'], ['1263', '34900', '37834'], ['4415', '2073', '3899'], ['4415', '4580', '6004']]
>>> from collections import defaultdict
>>>
>>> d = defaultdict(list)
>>>
>>> for i, j, k in coords:
... d[i].append((j, k))
...
>>> d
defaultdict(<type 'list'>, {'1263': [('34900', '37834')], '4415': [('16723', '17556'), ('2073', '3899'), ('4580', '6004')], '127': [('1290', '1145')]})
此外,在鍵的末尾添加字符的想法並不是最佳的,因為您需要始終擁有鍵的數量而您不知道這個數字,因此您必須生成新的后綴。
但是,如果您只使用鍵的計數,則可以通過保留Counter()
對象中的鍵並在鍵的尾隨處添加計數來創建不同的鍵:
>>> from collections import Counter
>>> d = {}
>>> c = Counter()
>>> for i, j, k in coords:
... c.update((i,))
... d["{}_{}".format(i, c[i])] = (j, k)
...
>>> d
{'4415_1': ('16723', '17556'), '4415_3': ('4580', '6004'), '4415_2': ('2073', '3899'), '127_1': ('1290', '1145'), '1263_1': ('34900', '37834')}
你可以這樣做:
matches = {'127': ['1290', '1145'], '1263': ['34900', '37834'], '4415': ['4580', '6004']}
# sample key_name
key_name = '4415'
if key_name in matches.keys():
for i in xrange(1,26):
if key_name+chr(ord('a') + i) not in matches.keys():
matches[key_name+chr(ord('a') + i)] = #your value
這會將你的key_names增加為4415a,4415b ......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.