How to print a dictionary line by line in Python?
for x in cars:
print (x)
for y in cars[x]:
print (y,':',cars[x][y])
output:A
color : 2
speed : 70
B
color : 3
speed : 60
How do I print the key-value pairs of a dictionary in python
Python 2 and Python 3
i
is the key, so you would just need to use it:
for i in d:
print i, d[i]
Python 3
d.items()
returns the iterator; to get a list, you need to pass the iterator to list()
yourself.
for k, v in d.items():
print(k, v)
Python 2
You can get an iterator that contains both keys and values. d.items()
returns a list of (key, value) tuples, while d.iteritems()
returns an iterator that provides the same:
for k, v in d.iteritems():
print k, v
How to print dict in separate line?
>>> from pprint import pprint
>>> pprint(sums)
{'air': 2,
'and': 1,
'at': 3,
'be': 1,
'body': 1,
....., # and so on...
'you': 2}
how to make each key-value of a dictionary print on a new line?
If you really don't want to import pprint but want it to "look like" a dictionary, you could do:
print("{" + "\n".join("{!r}: {!r},".format(k, v) for k, v in d.items()) + "}")
python: print multiple dictionaries and strings line by line
Try this,
import json
print( 'Names and counts',
'\n',
json.dumps(df['names'].value_counts()[:3].to_dict(),indent=2),
'\n',
'Last names and counts',
'\n',
json.dumps(df['last names'].value_counts()[:3].to_dict(),indent=2),
'Staff names and counts',
'\n',
json.dumps(df['staff_names'].value_counts()[:3].to_dict(),indent=2),
'\n',
'Staff last names and counts',
'\n',
json.dumps(df['staff last names'].value_counts()[:3].to_dict(),indent=2)
Change indent parameter to a higher number for better formatting..Note: Tested by Creator and working fine.
Printing elements of dictionary line by line
If you are trying to print the key values out of a dictionary in the same order as they appear in the file using a standard dict that won't work (python dict objects don't maintain order). Assuming you want to print by the value of the dicts values...
lines = ["the 1", "and 2"]
d = {}
for l in lines:
k, v = l.split()
d[k] = v
for key in sorted(d, key=d.get, reverse=True):
print ":".join([key, d[key]])
assuming you can use lambda
and string concatenation.lines = ["the 1", "and 2"]
d = {}
for l in lines:
k, v = l.split()
d[k] = v
for key in sorted(d, key=lambda k: d[k], reverse=True):
print key + ":" + d[key]
with out lambdafor value, key in sorted([(d[k], k) for k in d], reverse=True):
print key + ":" + value
to make a function out of itdef lines_to_dict(lines):
return_dict = {}
for line in lines:
key, value = line.split()
return_dict[key] = value
return return_dict
if __name__ == "__main__":
lines = ["the 1", "and 2"]
print lines_to_dict(lines)
How to pretty print nested dictionaries?
I'm not sure how exactly you want the formatting to look like, but you could start with a function like this:
def pretty(d, indent=0):
for key, value in d.items():
print('\t' * indent + str(key))
if isinstance(value, dict):
pretty(value, indent+1)
else:
print('\t' * (indent+1) + str(value))
Related Topics
Python: Can't Pickle Type X, Attribute Lookup Failed
How to Concatenate Three Excels Files Xlsx Using Python
Numpy Version of "Exponential Weighted Moving Average", Equivalent to Pandas.Ewm().Mean()
Django: How to Build a Custom Form Widget
Networkx - Change Color/Width According to Edge Attributes - Inconsistent Result
Passing Double Quote Shell Commands in Python to Subprocess.Popen()
How to Obscure a Line Behind a Surface Plot in Matplotlib
How to Convert an Integer to the Shortest Url-Safe String in Python
In-Place Type Conversion of a Numpy Array
How to Change a Widget's Font Style Without Knowing the Widget's Font Family/Size
Why Does Python Use 'Magic Methods'
Is There an Platform Independent Equivalent of Os.Startfile()