如何访问包含字典和列表的嵌套字典中的项目,并打印这些项目?
我创建了一个字典,长得像这样:
DictItems = {
'Rule1' : {1 : [S1, S2, S3], 2 : [S4, S5], 3: [S8]},
'Rule2' : {1 : [S2, S3], 2 : [S2, S4, S5]}
}
我尝试了以下方法:
for key, value, listval in DictItems.items():
print key, value, listval
但是出现了错误:“ValueError: need more than 2 values to unpack
”。
我该如何访问单独的项目,以便打印或操作它们呢?
单独的项目指的是:我想检查关联规则。所以我想在一个条件判断中访问像'Rule1'这样的单独项目,然后再查看下一个字典中的值,比如1或2,以及列表中的项目。
4 个回答
为了回答你的问题,你可以在原来的循环里面再加一个循环,像这样:
for key, value in DictItems.items():
print key
for key2, value2 in value.items():
print key2, value2
然后你可以继续加更多层,想加多少层都可以。如果你想让代码看起来更复杂一些,还可以用递归的方法,但如果只是两层的话,这样就够用了。
顺便说一下,别在意我用的命名方式,哈哈 :P
在编程中,很多时候我们需要处理一些数据,比如从一个地方获取数据,然后对这些数据进行一些操作,最后再把结果放到另一个地方。这就像是一个流水线,数据在这个过程中不断被加工和处理。
有时候,我们会遇到一些问题,比如数据格式不对,或者数据缺失。这就需要我们在处理数据之前,先检查一下数据的状态,确保它是我们可以使用的。
此外,编程中还有一个很重要的概念就是“错误处理”。当程序运行时,如果遇到问题,比如找不到文件或者网络连接失败,我们需要有办法来处理这些错误,避免程序崩溃。通常,我们会使用一些特定的语法来捕捉这些错误,并给出相应的提示或者采取其他措施。
总之,处理数据和错误是编程中非常重要的部分,掌握这些基本概念可以帮助我们写出更稳定、更可靠的程序。
for rule_num, group in DictItems.items():
print rule_num
for index, lst in group.items():
print " %s: %s" % (index, lst)
...
Rule2
1: ['S2', 'S3']
2: ['S2', 'S4', 'S5']
Rule1
1: ['S1', 'S2', 'S3']
2: ['S4', 'S5']
3: ['S8']
dict.items()
会给你一个包含 (键, 值)
对的列表,但它不会把里面的字典再拆开。
你只能拆出键和值,这里的值是另一个字典对象。如果想要访问里面的字典,你也需要对它进行遍历,可能像这样:
for rule, rule_mapping in DictItems.items():
print rule
for rulemap_number, listvalue in rule_mapping.items():
print '{}: {}'.format(rulemap_number, listvalue)
我觉得你把这个搞得太复杂了。
假设有这样一个字典:
>>> DictItems = {
... 'Rule1' : {1 : ['S1', 'S2', 'S3'], 2 : ['S4', 'S5'], 3: ['S8']},
... 'Rule2' : {1 : ['S2', 'S3'], 2 : ['S2', 'S4', 'S5']}
... }
你可以用键(对于字典)或者索引(对于序列)来访问里面的每一个元素,方法是用一对方括号([]
,也叫做订阅或者__getitem__
操作符):
>>> DictItems['Rule1']
{1: ['S1', 'S2', 'S3'], 2: ['S4', 'S5'], 3: ['S8']}
>>> DictItems['Rule1'][1]
['S1', 'S2', 'S3']
>>> DictItems['Rule1'][1][-1]
'S3'
>>> DictItems['Rule1'][1][-1][0]
'S'
我们来分析一下最后一个:
DictItems['Rule1'][1][-1][0]
^^^ key to the top dict
^ key to dict with int key
^^ relative index to a sequence -- last one
^ absolute index to a sequence -- first item
要打印出来的话:
>>> for k, li in DictItems['Rule1'].items():
... print k, li
...
1 ['S1', 'S2', 'S3']
2 ['S4', 'S5']
3 ['S8']
如果你想访问并进行比较,比如:
>>> DictItems['Rule1'][1][2]==DictItems['Rule2'][1][-1]
True
如果你想把这个例子拆开,可以使用嵌套循环:
>>> for k in DictItems:
... for sk, li in DictItems[k].items():
... print k, sk, li
...
Rule2 1 ['S2', 'S3']
Rule2 2 ['S2', 'S4', 'S5']
Rule1 1 ['S1', 'S2', 'S3']
Rule1 2 ['S4', 'S5']
Rule1 3 ['S8']
因为字典是无序的,所以里面的项目不一定会按照插入的顺序出来。你可以对键进行排序:
>>> for k in sorted(DictItems):
... for sk in sorted(DictItems[k]):
... print k, sk, DictItems[k][sk]
...
Rule1 1 ['S1', 'S2', 'S3']
Rule1 2 ['S4', 'S5']
Rule1 3 ['S8']
Rule2 1 ['S2', 'S3']
Rule2 2 ['S2', 'S4', 'S5']
你也可以使用json来美化打印一个嵌套的字典:
>>> import json
>>> print json.dumps(DictItems, sort_keys=True, indent=4)
{
"Rule1": {
"1": [
"S1",
"S2",
"S3"
],
"2": [
"S4",
"S5"
],
"3": [
"S8"
]
},
"Rule2": {
"1": [
"S2",
"S3"
],
"2": [
"S2",
"S4",
"S5"
]
}
}