从作为iterab的词典创建词典

2024-05-13 04:34:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究一个简单的解析器,其中顺序/索引很重要。但是,每个条目都有许多空值,因此为了节省空间,我想删除它们。为了维护顺序/索引信息,我尝试在一个字典中创建一个字典,其中内部字典的键是“外部字典的键+索引”

它以一个长字符串开始:

'Blue|periwinkle|power|morning|cyan\nPurple|indigo|violet|royal|electric\nred|rogue|mauve|wine|magenta\nyellow|gold|amber|flax|mustard'

因此,我将文件打开到python中,并按如下方式分解字符串:

with open('example1.hl7', 'r') as message:
    for i,line in enumerate(message):
        line = line.split('|', 1)
        linekey = line[0]
        line = {linekey + str(i + 1): line[1]}
        line = {key: list(map(str, value.split('|'))) for key, value in line.items()}

给了我这个:

{'Blue': ['periwinkle', 'power', 'morning', 'cyan'],
'Purple': ['indigo', 'violet', 'royal', 'electric'],
'red': ['rogue', 'mauve', 'wine', 'magenta'],
'yellow': ['gold', 'amber', 'flax', 'mustard']}

我想我需要在下一部分中使用map(),但是不知道要调用什么函数来正确格式化字典以及如何引用外键。我为outer键命名是为了让它更容易调用,但是仍然在添加索引并使其成为内部字典的键。我想要的是:

{'Blue': 
    {'Blue1': 'periwinkle', 'Blue2': 'power', 'Blue3': 'morning', 'Blue4': 'cyan'},
'Purple':
    {'Purple1': 'indigo', 'Purple2': 'violet', 'Purple3': 'royal', 'Purple4': 'electric'},
'Red':
    {'Red1': 'rogue', 'Red2': 'mauve', 'Red3': 'wine', 'Red4': 'magenta'},
'Yellow':
    {'Yellow1': 'gold', 'Yellow2': 'amber', 'Yellow3': 'flax', 'Yellow4': 'mustard'}
}

Tags: 字典linebluepowermorningwineroyalindigo
1条回答
网友
1楼 · 发布于 2024-05-13 04:34:13

试试这个
我将长字符串放入文件example1.hl7

outer_dict = {}

with open('example1.hl7', 'r') as _file:
    line = _file.read()

for i in line.strip().split('\n'):
    values = i.split('|')
    outer_key = values[0]
    outer_dict[outer_key] = {"{}{}".format(outer_key, index+1): j
                             for index, j in enumerate(values[1:])}
print outer_dict

注意:假设长字符串格式不变)

相关问题 更多 >