如何在带整数键的Python中使用带字典的format函数

如何在带整数键的Python中使用带字典的format函数,python,python-3.x,string-formatting,Python,Python 3.x,String Formatting,给定命令: dct = {1: 1, 2: 1} 如何以字符串格式使用此dict?我试过: print("{0[Key]},{1[Value]} ".format(**dct)) 上面的代码给了我这个错误: print("{0[Key]},{1[Value]} ".format(**dct)) IndexError: tuple index out of range 如果需要对使用整数键的dict使用字符串格式,可以在通过dict理解进行格式设置之前将其转换为有效关键字: 代码: d

给定
命令

dct = {1: 1, 2: 1} 
如何以字符串格式使用此dict?我试过:

print("{0[Key]},{1[Value]}  ".format(**dct))
上面的代码给了我这个错误:

print("{0[Key]},{1[Value]}  ".format(**dct))
IndexError: tuple index out of range

如果需要对使用整数键的dict使用字符串格式,可以在通过dict理解进行格式设置之前将其转换为有效关键字:

代码:

dct = {1: 1, 2: 3}
print("{key_1},{key_2}".format(
    **{'key_%d' % k: v for k, v in dct.items()}))
1,3
结果:

dct = {1: 1, 2: 3}
print("{key_1},{key_2}".format(
    **{'key_%d' % k: v for k, v in dct.items()}))
1,3

如果需要对使用整数键的dict使用字符串格式,可以在通过dict理解进行格式设置之前将其转换为有效关键字:

代码:

dct = {1: 1, 2: 3}
print("{key_1},{key_2}".format(
    **{'key_%d' % k: v for k, v in dct.items()}))
1,3
结果:

dct = {1: 1, 2: 3}
print("{key_1},{key_2}".format(
    **{'key_%d' % k: v for k, v in dct.items()}))
1,3

不确定期望的输出

for k,v in dct.items()
    print("{0} is my key and {1} is my value".format(k,v))

不确定期望的输出

for k,v in dct.items()
    print("{0} is my key and {1} is my value".format(k,v))

谢谢大家发帖。 请允许我详细说明我的需要。我正在分析一个包含Wi-Fi频道的文本文件。我正在尝试获取通道出现的时间数

我的文本文件(file_parse.txt)具有:

以open(r“C:\Temp\file\u parse.txt”)作为文件名:

regex = re.compile("[C|c]hannel:[0-9]+")
count = 0

lst = []
new_lst =[]
for line in filename.readlines():
    if regex.search(line):
        count += 1

        lst.append(line)
        new_lst = [(lst[i].split(":"))for i in range(len(lst))]
        integer_lst = [int(new_lst[firstElement][1]) for firstElement in range(len(new_lst))]

def channel_count(lst):
    dct = {}
    for num in lst:
        dct[num] = lst.count(num)
        print('There are/is {1} channel {0} '.format(num, dct[num]))
通道计数(整数)

例外输出:

有两条161频道

有一个40频道


有更好的方法吗?

谢谢大家的发帖。 请允许我详细说明我的需要。我正在分析一个包含Wi-Fi频道的文本文件。我正在尝试获取通道出现的时间数

我的文本文件(file_parse.txt)具有:

以open(r“C:\Temp\file\u parse.txt”)作为文件名:

regex = re.compile("[C|c]hannel:[0-9]+")
count = 0

lst = []
new_lst =[]
for line in filename.readlines():
    if regex.search(line):
        count += 1

        lst.append(line)
        new_lst = [(lst[i].split(":"))for i in range(len(lst))]
        integer_lst = [int(new_lst[firstElement][1]) for firstElement in range(len(new_lst))]

def channel_count(lst):
    dct = {}
    for num in lst:
        dct[num] = lst.count(num)
        print('There are/is {1} channel {0} '.format(num, dct[num]))
通道计数(整数)

例外输出:

有两条161频道

有一个40频道


有更好的方法吗?

你想做什么?你不能以任何有用的方式使用整数键作为关键字。使用
format
方法,您似乎不会立即得到关于
**dct
的异常,因为它是用C编写的内置函数,但是,如果
format
是纯Python函数,那么您将从函数调用中得到
TypeError
。您想做什么?您不能以任何有用的方式使用整型键作为关键字。使用
format
方法似乎不会立即得到有关
**dct
的异常,因为它是用C编写的内置函数,但如果
format
是纯Python函数,则会从函数调用中得到
TypeError