尝试添加到dict抛出KeyError - Python3.5.3

时间:2018-03-24 06:50:44

标签: python python-3.x dictionary

我编写脚本来从管道中读取一些数据并解析参数。我有这样的剧本:

def metadataScrape():
    current_line = ""
    line_finished = False
    with open("/tmp/shairport-sync-metadata") as f:
        for line in f:
            current_line += line[:-1]
            if current_line[-2:] == "m>":
                line_finished = True

            if line_finished:
                html_data = html.fromstring(current_line)
                data = html_data.xpath("//text()")
                decoded_data = [HexDecode(data[0]), HexDecode(data[1])]
                if len(data) == 4:
                    decoded_data.append(Base64Decode(data[3]))
                else:
                    decoded_data.append("")
                decoded_data.append(time.time())
                print(decoded_data)
                if decoded_data[0] == "ssnc":
                    ssnc_params[decoded_data[1]] == decoded_data[2:]
                elif decoded_data[0] == "core":
                    core_params[decoded_data[1]] == decoded_data[2:]

                current_line = ""
                line_finished = False

每当我运行它,它似乎运行正常,直到我得到一些数据。例如,如果我尝试更改AirPlay机器上的音量(我的项目是一个AirPlay扬声器),当我尝试将其添加到字典时,它会抛出这个:

Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    metadataScrape()
  File "/home/pi/python/metadata-reader.py", line 57, in metadataScrape
    ssnc_params[decoded_data[1]] == decoded_data[2:]
KeyError: 'pvol'

仅供参考,这是我从管道中得到的那种东西的样本:

<item><type>636f7265</type><code>6173676e</code><length>3</length>
<data encoding="base64">
UG9w</data></item>
<item><type>636f7265</type><code>6d696e6d</code><length>27</length>
<data encoding="base64">
Q3JhenkgaW4gTG92ZSAoZmVhdC4gSmF5LVop</data></item>
<item><type>636f7265</type><code>6173646b</code><length>1</length>
<data encoding="base64">
AA==</data></item>
<item><type>636f7265</type><code>63617073</code><length>1</length>
<data encoding="base64">
Ag==</data></item>
<item><type>73736e63</type><code>6d64656e</code><length>10</length>
<data encoding="base64">
MTE1NDkyNzQwMg==</data></item>
<item><type>73736e63</type><code>7072736d</code><length>0</length></item>
<item><type>73736e63</type><code>70656e64</code><length>0</length></item>

非常感谢任何帮助。感谢。

1 个答案:

答案 0 :(得分:1)

您混淆了===。您没有向字典中添加任何内容,而是尝试将某些内容与尚不存在的元素进行比较。 ssnc_params[decoded_data[1]] == decoded_data[2:]必须为ssnc_params[decoded_data[1]] = decoded_data[2:]。与core_params相同。