python - 把一行拆分成一个字典,里面有多层键值对

标签 python dictionary split key-value

我有一个包含这种格式的行的文件。

Example 1:
nextline = "DD:MM:YYYY INFO - 'WeeklyMedal: Hole = 1; Par = 4; Index = 2; Distance = 459; Score = { Player1 = 4 };"

Example 2:
nextline = "DD:MM:YYYY INFO - 'WeeklyMedal: Hole = 1; Par = 4; Index = 2; Distance = 459; Score = { Player1 = 4; Player2 = 6; Player3 = 4 };"

我首先用“:”分割了这一行,这给了我一个包含 2 个条目的列表。 我想将此行拆分为一个包含键和值的字典,但其中 score 键有多个带有值的子键。

Hole 1
Par 4
Index 2
Distance 459
Score 
    Player1 4
    Player2 6
    Player3 4

所以我正在使用这样的东西......

split_line_by_semicolon = nextline.split(":")
dictionary_of_line = dict((k.strip(), v.strip()) for k,v in (item.split('=')     
    for item in split_line_by_semicolon.split(';')))
        for keys,values in dictionary_of_line.items():
            print("{0} {1}".format(keys,values))

但是我在该行的 score 元素上收到错误:

ValueError: too many values to unpack (expected 2)

我可以调整 '=' 上的分割,所以它在第一个 '=' 之后停止

dictionary_of_line = dict((k.strip(), v.strip()) for k,v in (item.split('=',1)     
    for item in split_line_by_semicolon.split(';')))
        for keys,values in dictionary_of_line.items():
            print("{0} {1}".format(keys,values))

但是我丢失了大括号内的子值。有人知道我如何实现这个多层字典吗?

最佳答案

一个更简单的方法(但我不知道在您的情况下是否可以接受)是:

import re

nextline = "DD:MM:YYYY INFO - 'WeeklyMedal: Hole = 1; Par = 4; Index = 2; Distance = 459; Score = { Player1 = 4; Player2 = 6; Player3 = 4 };"

# compiles the regular expression to get the info you want
my_regex = re.compile(r'\w+ \= \w+')

# builds the structure of the dict you expect to get 
final_dict = {'Hole':0, 'Par':0, 'Index':0, 'Distance':0, 'Score':{}}

# uses the compiled regular expression to filter out the info you want from the string
filtered_items = my_regex.findall(nextline)

for item in filtered_items:
    # for each filtered item (string in the form key = value)
    # splits out the 'key' and handles it to fill your final dictionary
    key = item.split(' = ')[0]
    if key.startswith('Player'):
        final_dict['Score'][key] = int(item.split(' = ')[1])
    else:
        final_dict[key] = int(item.split(' = ')[1])

关于python - 把一行拆分成一个字典,里面有多层键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32993373/

相关文章:

python - 从Python中的字典的多个键中获取特定值的唯一名称

c# - 仅当下一个字符为小写时才将字符串拆分为大写

sql-server - 使用 SQL 将日期范围拆分为多行

python - Python 中的错误消息 "MemoryError"

python - 回调函数在实例中看不到正确的值

python - Gaendb 结构化属性

python - 按字符串长度分割系列

python - 如何在 Mac 操作系统上使用 json

c++ - 查找表究竟是如何工作的以及如何实现它们?

java - java8 按降序对映射进行排序