簡體   English   中英

如何在 Python 中逐行打印字典?

[英]How to print a dictionary line by line in Python?

這是字典

cars = {'A':{'speed':70,
        'color':2},
        'B':{'speed':60,
        'color':3}}

使用這個for loop

for keys,values in cars.items():
    print(keys)
    print(values)

它打印以下內容:

B
{'color': 3, 'speed': 60}
A
{'color': 2, 'speed': 70}

但我希望程序像這樣打印它:

B
color : 3
speed : 60
A
color : 2
speed : 70

我剛開始學習字典,所以我不知道該怎么做。

for x in cars:
    print (x)
    for y in cars[x]:
        print (y,':',cars[x][y])

輸出:

A
color : 2
speed : 70
B
color : 3
speed : 60

您可以為此使用json模塊。 此模塊中的dumps函數將 JSON 對象轉換為格式正確的字符串,然后您可以打印該字符串。

import json

cars = {'A':{'speed':70, 'color':2},
        'B':{'speed':60, 'color':3}}

print(json.dumps(cars, indent = 4))

輸出看起來像

{
    "A": {
        "color": 2,
        "speed": 70
    },
    "B": {
        "color": 3,
        "speed": 60
    }
}

文檔還為此方法指定了一堆有用的選項。

處理任意深度嵌套的字典和列表的更通用的解決方案是:

def dumpclean(obj):
    if isinstance(obj, dict):
        for k, v in obj.items():
            if hasattr(v, '__iter__'):
                print k
                dumpclean(v)
            else:
                print '%s : %s' % (k, v)
    elif isinstance(obj, list):
        for v in obj:
            if hasattr(v, '__iter__'):
                dumpclean(v)
            else:
                print v
    else:
        print obj

這將產生輸出:

A
color : 2
speed : 70
B
color : 3
speed : 60

我遇到了類似的需求,並開發了一個更強大的功能作為自己的練習。 我把它包括在這里,以防它對另一個人有價值。 在運行nosetest 時,我還發現能夠在調用中指定輸出流以便可以使用sys.stderr 來代替它很有幫助。

import sys

def dump(obj, nested_level=0, output=sys.stdout):
    spacing = '   '
    if isinstance(obj, dict):
        print >> output, '%s{' % ((nested_level) * spacing)
        for k, v in obj.items():
            if hasattr(v, '__iter__'):
                print >> output, '%s%s:' % ((nested_level + 1) * spacing, k)
                dump(v, nested_level + 1, output)
            else:
                print >> output, '%s%s: %s' % ((nested_level + 1) * spacing, k, v)
        print >> output, '%s}' % (nested_level * spacing)
    elif isinstance(obj, list):
        print >> output, '%s[' % ((nested_level) * spacing)
        for v in obj:
            if hasattr(v, '__iter__'):
                dump(v, nested_level + 1, output)
            else:
                print >> output, '%s%s' % ((nested_level + 1) * spacing, v)
        print >> output, '%s]' % ((nested_level) * spacing)
    else:
        print >> output, '%s%s' % (nested_level * spacing, obj)

使用此函數,OP 的輸出如下所示:

{
   A:
   {
      color: 2
      speed: 70
   }
   B:
   {
      color: 3
      speed: 60
   }
}

我個人發現它更有用且更具描述性。

鑒於以下稍微不那么簡單的示例:

{"test": [{1:3}], "test2":[(1,2),(3,4)],"test3": {(1,2):['abc', 'def', 'ghi'],(4,5):'def'}}

OP 要求的解決方案產生了這個:

test
1 : 3
test3
(1, 2)
abc
def
ghi
(4, 5) : def
test2
(1, 2)
(3, 4)

而“增強”版本會產生這樣的結果:

{
   test:
   [
      {
         1: 3
      }
   ]
   test3:
   {
      (1, 2):
      [
         abc
         def
         ghi
      ]
      (4, 5): def
   }
   test2:
   [
      (1, 2)
      (3, 4)
   ]
}

我希望這能為下一個尋找此類功能的人提供一些價值。

pprint.pprint()是完成這項工作的好工具:

>>> import pprint
>>> cars = {'A':{'speed':70,
...         'color':2},
...         'B':{'speed':60,
...         'color':3}}
>>> pprint.pprint(cars, width=1)
{'A': {'color': 2,
       'speed': 70},
 'B': {'color': 3,
       'speed': 60}}

你有一個嵌套結構,所以你也需要格式化嵌套字典:

for key, car in cars.items():
    print(key)
    for attribute, value in car.items():
        print('{} : {}'.format(attribute, value))

這打印:

A
color : 2
speed : 70
B
color : 3
speed : 60

我更喜歡yaml的干凈格式:

import yaml
print(yaml.dump(cars))

輸出:

A:
  color: 2
  speed: 70
B:
  color: 3
  speed: 60
for car,info in cars.items():
    print(car)
    for key,value in info.items():
        print(key, ":", value)

如果您知道樹只有兩個級別,這將起作用:

for k1 in cars:
    print(k1)
    d = cars[k1]
    for k2 in d
        print(k2, ':', d[k2])

檢查以下單線:

print('\n'.join("%s\n%s" % (key1,('\n'.join("%s : %r" % (key2,val2) for (key2,val2) in val1.items()))) for (key1,val1) in cars.items()))

輸出:

A
speed : 70
color : 2
B
speed : 60
color : 3

這是我對問題的解決方案。 我認為它的方法相似,但比其他一些答案要簡單一些。 它還允許任意數量的子字典,並且似乎適用於任何數據類型(我什至在具有函數作為值的字典上對其進行了測試):

def pprint(web, level):
    for k,v in web.items():
        if isinstance(v, dict):
            print('\t'*level, f'{k}: ')
            level += 1
            pprint(v, level)
            level -= 1
        else:
            print('\t'*level, k, ": ", v)
###newbie exact answer desired (Python v3):
###=================================
"""
cars = {'A':{'speed':70,
        'color':2},
        'B':{'speed':60,
        'color':3}}
"""

for keys, values in  reversed(sorted(cars.items())):
    print(keys)
    for keys,values in sorted(values.items()):
        print(keys," : ", values)

"""
Output:
B
color  :  3
speed  :  60
A
color  :  2
speed  :  70

##[Finished in 0.073s]
"""
# Declare and Initialize Map
map = {}

map ["New"] = 1
map ["to"] = 1
map ["Python"] = 5
map ["or"] = 2

# Print Statement
for i in map:
  print ("", i, ":", map[i])

#  New : 1
#  to : 1
#  Python : 5
#  or : 2

用這個。

cars = {'A':{'speed':70,
        'color':2},
        'B':{'speed':60,
        'color':3}}

print(str(cars).replace(",", ",\n"))

輸出:

{'A': {'speed': 70,
 'color': 2},
 'B': {'speed': 60,
 'color': 3}}

我認為列表理解是最干凈的方法:

mydict = {a:1, b:2, c:3}

[(print("key:", key, end='\t'), print('value:', value)) for key, value in mydict.items()]

修改 MrWonderful 代碼

import sys

def print_dictionary(obj, ident):
    if type(obj) == dict:
        for k, v in obj.items():
            sys.stdout.write(ident)
            if hasattr(v, '__iter__'):
                print k
                print_dictionary(v, ident + '  ')
            else:
                print '%s : %s' % (k, v)
    elif type(obj) == list:
        for v in obj:
            sys.stdout.write(ident)
            if hasattr(v, '__iter__'):
                print_dictionary(v, ident + '  ')
            else:
                print v
    else:
        print obj

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM