[英]How to convert. a sample dictionary to a different format by key word?
If I have a sample dictionary like this:如果我有这样的示例字典:
sample_field = {'XG102': '1/1:0,76:76:99:1|1:48306945_C_G:3353,229,0',
'XG103': '1/1:0,52:52:99:.:.:1517,156,0',
'XG104': '0/1:34,38:72:99:.:.:938,0,796'}
by giving the key word, I want to transform this sample dictionary like this:通过给出关键字,我想像这样转换这个示例字典:
output = {'XG102': {'1: '0,76',
'2': '76',
'3': '99',
'4': '1/1',
'5': '1|1',
'6': '48306945_C_G',
'7': '3353,229,0'},
'XG103': {'1': '0,52',
'2': '52',
'3': '99',
'4': '1/1',
'5': '.',
'6': '.',
'7': '1517,156,0'}
....
I try to map the sample dictionary to a new dictionary by using key like a index, but it doesn't work.我尝试使用索引之类的键将示例字典映射到新字典,但它不起作用。 Any suggestion ?有什么建议吗?
You may be looking for a dictionary comprehension using enumerate
and split
:您可能正在寻找使用enumerate
和split
的字典理解:
sample_field = {
"XG102": "1/1:0,76:76:99:1|1:48306945_C_G:3353,229,0",
"XG103": "1/1:0,52:52:99:.:.:1517,156,0",
"XG104": "0/1:34,38:72:99:.:.:938,0,796",
}
out = {
key: dict(enumerate(value.split(":"), 1))
for (key, value) in sample_field.items()
}
-- out
will be —— out
将
{
"XG102": {
1: "1/1",
2: "0,76",
3: "76",
4: "99",
5: "1|1",
6: "48306945_C_G",
7: "3353,229,0",
},
"XG103": {
1: "1/1",
2: "0,52",
3: "52",
4: "99",
5: ".",
6: ".",
7: "1517,156,0",
},
"XG104": {
1: "0/1",
2: "34,38",
3: "72",
4: "99",
5: ".",
6: ".",
7: "938,0,796",
},
}
This should work:这应该有效:
def create_split_dict(val):
tokens = val.split(":")
return {index+1:item for index, item in enumerate(tokens)}
output = {key:create_split_dict(val) for key, val in sample_field}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.