Printing out Dictionary Keys in a More Attractive Way

Viewed 56

Good Evening,

It's not too difficult to print out a dictionary's keys:

print(dict_example.keys())

But this method spits out a rather unattractive presentation:

dict_keys(['A', 'B', 'C'])

Is there a way to get Python to spit out the keys to a dictionary in a more attractive way. For instance, like this:

A, B, C
3 Answers

You can use the string method join for this:

dict_example = {
    'A': 1, 
    'B': 2, 
    'C': 3,
}
print(', '.join(dict_example))

# output:
# A, B, C

Since str.join expects an iterable of some sort, passing in a dictionary as its argument means that it will join all of its keys into a single string (since iterating over a dictionary means iterating over its keys).

You'll need to modify it slightly if one or more keys aren't strings, by explicitly casting them to string prior to joining. In this case, we can pass in the generator expression str(k) for k in dict to str.join in order to do just that:

dict_example = {
    'A': 1, 
    'B': 2, 
    'C': 3, 
    10.5: 'xxx',
}
print(', '.join(str(k) for k in dict_example))

# output:
# A, B, C, 10.5

A simple solution would be using a * in print like:

print(*dict_example.keys()) #A B C

adding a separator would make it more readable:

print(*dict_example.keys(),sep=', ') #A, B, C

If you want a more detailed one:

print("\n".join("{}\t{}".format(k, v) for k, v in dict_example.items())) 
#A     dict_example['A']
#B     dict_example['B']

You can use the join method:

>>> print(", ".join(d.keys()))
a, b, c
Related