Jak wydrukować wiersz po wierszu słownika w Pythonie?
To jest słownik
cars = {'A':{'speed':70,
'color':2},
'B':{'speed':60,
'color':3}}
Using this for loop
for keys,values in cars.items():
print(keys)
print(values)
Drukuje:
B
{'color': 3, 'speed': 60}
A
{'color': 2, 'speed': 70}
Ale chcę aby program wydrukował to tak:
B
color : 3
speed : 60
A
color : 2
speed : 70
Właśnie zacząłem uczyć się słowników, więc nie jestem pewien, jak to zrobić.
9 answers
for x in cars:
print (x)
for y in cars[x]:
print (y,':',cars[x][y])
Wyjście:
A
color : 2
speed : 70
B
color : 3
speed : 60
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-03 11:26:25
Bardziej uogólnionym rozwiązaniem, które obsługuje arbitralnie-głęboko zagnieżdżone dicty i listy, byłoby:
def dumpclean(obj):
if type(obj) == dict:
for k, v in obj.items():
if hasattr(v, '__iter__'):
print k
dumpclean(v)
else:
print '%s : %s' % (k, v)
elif type(obj) == list:
for v in obj:
if hasattr(v, '__iter__'):
dumpclean(v)
else:
print v
else:
print obj
To daje wyjście:
A
color : 2
speed : 70
B
color : 3
speed : 60
[7]}spotkałam się z podobną potrzebą i opracowałam bardziej solidną funkcję jako ćwiczenie dla siebie. Włączam go tutaj, na wypadek, gdyby mógł być wartościowy dla innego. W uruchomieniu nosetest, również okazało się pomocne, aby móc określić strumień wyjściowy w wywołaniu tak, aby sys.zamiast tego można użyć stderr.
import sys
def dump(obj, nested_level=0, output=sys.stdout):
spacing = ' '
if type(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 type(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)
Używając tej funkcji, Wyjście OP wygląda tak:
{
A:
{
color: 2
speed: 70
}
B:
{
color: 3
speed: 60
}
}
Które osobiście uważam za bardziej użyteczne i opisowe.
Biorąc pod uwagę nieco mniej trywialny przykład:
{"test": [{1:3}], "test2":[(1,2),(3,4)],"test3": {(1,2):['abc', 'def', 'ghi'],(4,5):'def'}}
Żądane rozwiązanie OP daje to:
test
1 : 3
test3
(1, 2)
abc
def
ghi
(4, 5) : def
test2
(1, 2)
(3, 4)
Natomiast wersja "ulepszona" daje to:
{
test:
[
{
1: 3
}
]
test3:
{
(1, 2):
[
abc
def
ghi
]
(4, 5): def
}
test2:
[
(1, 2)
(3, 4)
]
}
Mam nadzieję, że przyniesie to jakąś wartość następnej osobie szukającej tego typu funkcjonalności.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-10 16:10:22
Możesz użyć do tego modułu json
. Funkcja dumps
w tym module konwertuje obiekt JSON na odpowiednio sformatowany łańcuch znaków, który można następnie wydrukować.
import json
cars = {'A':{'speed':70, 'color':2},
'B':{'speed':60, 'color':3}}
print(json.dumps(cars, indent = 4))
Wyjście wygląda jak
{ "A": { "color": 2, "speed": 70 }, "B": { "color": 3, "speed": 60 } }
Dokumentacja określa również kilka przydatnych opcji dla tej metody.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-03 07:23:18
Masz zagnieżdżoną strukturę, więc musisz sformatować również zagnieżdżony słownik:
for key, car in cars.items():
print(key)
for attribute, value in car.items():
print('{} : {}'.format(attribute, value))
To drukuje:
A
color : 2
speed : 70
B
color : 3
speed : 60
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-03 11:13:00
Jak Martijn Pieters wspomniał w jednym z komentarzy powyżej PrettyPrint jest dobrym narzędziem do tej pracy:
>>> 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}}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-13 11:50:34
for car,info in cars.items():
print(car)
for key,value in info.items():
print(key, ":", value)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-03 11:13:27
To zadziała, jeśli wiesz, że drzewo ma tylko dwa poziomy:
for k1 in cars:
print(k1)
d = cars[k1]
for k2 in d
print(k2, ':', d[k2])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-03 11:15:55
Sprawdź następujące jednoliniowe:
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()))
Wyjście:
A
speed : 70
color : 2
B
speed : 60
color : 3
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-27 21:07:48
Modyfikowanie kodu 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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-27 17:13:32