3 python
尝试在包含在defaultdict中的字典的结构中显示数据
dictionary=defaultdic(dict)
Run Code Online (Sandbox Code Playgroud)
例
defaultdict = {key1} :
{subkey1}:
(val1,
val2,
val3)
{subkey2}:
(val4,
val5,
val6)
{key2} :
{subkey3}:
(val7,
val8,
val9),
{subkey4}:
(val10,
val11,
val12)
Run Code Online (Sandbox Code Playgroud)
我试着这样做
for key in dictionary.iterkeys():
print key # This will return me the key
for items in dictionary[key]:
print items # This will return me the subkey
for values in dictionary[key][items]:
print values #this return the values for each subkey)
Run Code Online (Sandbox Code Playgroud)
问题是我只是打印出一个单独的项目清单; 当你有太多的物品和钥匙时几乎不可能遵循.
你如何正确地打印这样复杂的结构,以一种不会让你睁开眼睛的方式呈现它们?我尝试使用pprint和json.dumps,但两者都没有让情况变得更好.理想情况下,我想在我的示例中打印它,但我看不到一种简单的方法,而不会通过复杂的字符串操作来格式化打印输出.
Python有PrettyPrint模块就是为了这个目的.请注意,默认值不能很好地打印,但如果你先转换回常规字典,那就行了.
from pprint import pprint
pprint(dict(dictionary))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4152 次 |
| 最近记录: |