<p>代码不起作用的原因是,当您遍历行并将它们插入到目标词典<code>res</code>时,您还将<code>value</code>设置为子词典,在这个子词典中,行将始终位于同一关键字“b”、“c”、“d”下,换句话说,底部的行覆盖了顶部的行,只剩下第三行用于<code>Nodeb_IN_New</code>。你知道吗</p>
<hr/>
<p>另一种方法是将<code>value</code>设置为一个列表,遍历行,如果它们属于同一个<code>qos</code>,则将它们附加到此列表中,下面是代码:</p>
<pre><code># Original excel sheet in a list
raw_list = [
['Nodeb_IN_New', 107, 'class-default', 'mobility-platinum', 'h1', 7, 'dscp-fc-map', ['ef']],
['', 107, '', 'mobility-gold-new', 'h2', 5, 'dscp-fc-map', ['af41']],
['', 107, '', 'mobility-silver-new', 'l1', 4, 'dscp-fc-map', ['af11', 'af21', 'af31']],
['Nokia_SRAN_S1-MME_X2_IN', 102, '', 'Nokia_SRAN_mobility_platinum', 'h1', 7, 'dscp-fc-map', ['ef', 'nc1']]
]
result_dict = {}
# title, will be used as key in the result_dict
title = ""
# Loop through the input list
for row in raw_list:
# If the first value is not empty, replace the title with this new value
if row[0] != "":
# update title
title = row[0]
# Insert into the dictionary, and give an empty list as a place holder,
# later we can append to this list
result_dict[title] = []
# At this stage we can append the rest of the input row to the dictionary value
result_dict[title].append(row[1:])
print("Result dict: ")
for (key, value) in result_dict.items():
print("Key: {}".format(key))
for row in value:
print(" {}".format(row))
</code></pre>
<p>下面是上面代码的输出:</p>
<pre><code>Key: Nodeb_IN_New
[107, 'class-default', 'mobility-platinum', 'h1', 7, 'dscp-fc-map', ['ef']]
[107, '', 'mobility-gold-new', 'h2', 5, 'dscp-fc-map', ['af41']]
[107, '', 'mobility-silver-new', 'l1', 4, 'dscp-fc-map', ['af11', 'af21', 'af31']]
Key: Nokia_SRAN_S1-MME_X2_IN
[102, '', 'Nokia_SRAN_mobility_platinum', 'h1', 7, 'dscp-fc-map', ['ef', 'nc1']]
</code></pre>