Eliott Reed
Eliott Reed

Reputation: 321

How do I print a dictionary so my items are printed in quotation marks and in brackets?

I am trying to print my dictionary in quotes and in brackets.

my output is this:

I1: A1, T1 I2: A2, T2 I3: A3, T3

but i want this:

I1: ('A1', 'T1') I2: ('A2', 'T2') I3: ('A3', 'T3')

This is my code.....

def isbn_dictionary(filename):

    isbn_dic={}
    for line in open(filename,"r"):
        author,title,isbn = line.strip().split(',')
        isbn_dic[isbn] = author + ", " + title
print (isbn_dic)

Upvotes: 0

Views: 95

Answers (3)

Valérie Gelbgras
Valérie Gelbgras

Reputation: 53

With this input as a list (just to be easier to show here)

input = [
    'A1, T11, I1',
    'A1, T12, I2',
    'A2, T21, I3',
    'A3, T31, I4',
]

def isbn_dictionary(input):
    isbn_dic={}
    for line in input:
        author, title, isbn = line.strip().split(',')
        isbn_dic[isbn] = f"({author}, {title})"
    return isbn_dic

test = isbn_dictionary(input)

print(test)

enter image description here

Upvotes: 1

Nk03
Nk03

Reputation: 14949

Try F-Strings

def isbn_dictionary(filename):

    isbn_dic = {}
    for line in open(filename, "r"):
        author, title, isbn = line.strip().split(',')
        isbn_dic[isbn] = f"('{author}','{title}')"


print(isbn_dic)

Upvotes: 0

Karun Ellango
Karun Ellango

Reputation: 136

Storing the result as a tuple like this gets you a very similar result and lets you keep the single quotes for the strings instead of manually formatting them

isbn_dic[isbn] = author, title

For example

>>> temp = {}
>>> temp['test'] = '1', '2'
>>> temp['test2'] = '1', '2'
>>> print(temp)
{'test': ('1', '2'), 'test2': ('1', '2')

or if you don't want the braces and want it exactly like your sample output, you can use the items() method and f-strings

>>> test = {}
>>> test['test'] = '1', '2'
>>> test['test2'] = '1', '2'
>>> print(' '.join(f"{k}: {v}" for k, v in test.items()))
test: ('1', '2') test2: ('1', '2')

Upvotes: 1

Related Questions