简体   繁体   English

如何打印字典,以便将我的项目打印在引号和括号中?

[英]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:我的 output 是这样的:

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

but i want this:但我想要这个:

I1: ('A1', 'T1') I2: ('A2', 'T2') I3: ('A3', 'T3') 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)

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或者如果您不想要大括号并且想要它与您的示例 output 完全一样,您可以使用 items() 方法和 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')

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)

在此处输入图像描述

Try F-Strings试试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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM