Jack Deeth
Jack Deeth

Reputation: 3357

Print a dictionary without quote marks?

Suppose I have a non-nested dictionary:

>>> foo = {'a': 123, 'b': 'asdf', 'c': 'Hello, world!'}

I can print it:

>>> print(foo)
{'a': 123, 'b': 'asdf', 'c': 'Hello, world!'}

Is there any built-in or otherwise convenient method to print it in a single line without the quote marks and brackets?

a: 123, b: asdf, c: Hello, world!

This is assuming there are no nested dictionaries.

Upvotes: 0

Views: 2046

Answers (5)

Jack Deeth
Jack Deeth

Reputation: 3357

In the light of a few years' experience with Python:

foo = {"a": 123, "b": "asdf", "c": "Hello, world!"}

print(", ".join(f"{k}: {v}" for k, v in foo.items()))

# a: 123, b: asdf, c: Hello, world!

But more importantly... it's rarely necessary to just dump an arbitrary dictionary to the console, and when it is, the quote marks don't matter as much as I evidently thought they did in 2020 - and if it is necessary, I'd now create a function named nice_print or something, and use more, simpler lines to get the same result.

Upvotes: 0

Rocco Fortuna
Rocco Fortuna

Reputation: 291

Alternatively, you can make your own object:

class NicelyPrintingDict():
    def __init__(self, some_dictionary):
        self.some_dictionary = some_dictionary

    def __str__(self):
        s = ''
        for key, value in self.some_dictionary.items():
            s += key + ': ' + str(value) + ' ' 
        return s.strip()

then, use it as follows:

foo = {'a': 123, 'b': 'asdf', 'c': 'Hello, world!'}
nice_foo = NicelyPrintingDict(foo)
print(nice_foo)
        

Upvotes: 1

Ganesh
Ganesh

Reputation: 33

foo = {'a': 123, 'b': 'asdf', 'c': 'Hello, world!'}

for i,j in foo.items():
    print(i, ":", j, end = ",")

a : 123, b : asdf, c : Hello, world!,

Upvotes: 1

Yossi Levi
Yossi Levi

Reputation: 1268

You can remove all the unwanted characters, and print it as you want, like this:

foo = {'a': 123, 'b': 'asdf', 'c': 'Hello, world!'}
print (str(foo).replace("{","").replace("'","").replace("}",""))

output:

a: 123, b: asdf, c: Hello, world!

pay attention, than whenever the characters {, } or ' are part of the dict, that solution will fail

in more details - when calling to str function - each object can implement __str__ function that return string (you can implement it by yourself for custom class). when take adventage of it - the str returned from the function can be treat as any other string and replace whatever you want to.

Upvotes: 2

Barzuka
Barzuka

Reputation: 41

if you know what fields you are using all the time you can just do something like:

foo = {
    'a': 123,
    'b': 'asdf',
    'c': 'Hello, World!'
}

print(f"a: {foo['a']} b: {foo['b']} c: {foo['c']}")

a: 123 b: asdf c: Hello, World!

Upvotes: 1

Related Questions