Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 将字典追加到元组列表中_Python 3.x_List_Dictionary_Tuples - Fatal编程技术网

Python 3.x 将字典追加到元组列表中

Python 3.x 将字典追加到元组列表中,python-3.x,list,dictionary,tuples,Python 3.x,List,Dictionary,Tuples,假设我得到了以下命令: d = {'x': 1, 'y': 2, 'z': 3} 我想创建一个函数,将每个键及其值附加到元组列表中,因此我编码: def dict_to_list_of_tuples(dic): list_of_tuples = [] for key in dic: list_of_tuples.append((key, dic[key])) return list_of_tuples 但我得到以下输出: [('x', 1), ('y'

假设我得到了以下命令:

d = {'x': 1, 'y': 2, 'z': 3}
我想创建一个函数,将每个键及其值附加到元组列表中,因此我编码:

def dict_to_list_of_tuples(dic):
    list_of_tuples = []
    for key in dic:
        list_of_tuples.append((key, dic[key]))
    return list_of_tuples
但我得到以下输出:

[('x', 1), ('y', 2), ('z', 3)]
虽然我想得到:

[(x, 1), (y, 2), (z, 3)]

您的函数只是
list(d.items())

对于以所需格式打印,只需使用
str.format
制作所需的表示即可:

>>> "[{}]".format(f", ".join(f"({k}, {v})" for k,v in d.items()) )
'[(x, 1), (y, 2), (z, 3)]'

你想把它打印出来吗?@Netwave不,我想用那种格式保存。那么
x
y
z
是什么?变量?因为我认为你误解了你的代码。
>>> "[{}]".format(f", ".join(f"({k}, {v})" for k,v in d.items()) )
'[(x, 1), (y, 2), (z, 3)]'
d = {'x': 1, 'y': 2, 'z': 3}

def dict_to_list_of_tuples(dic):
    list_of_tuples = []
    for key in dic:
        list_of_tuples.append((key, dic[key]))
    return list_of_tuples
print(dict_to_list_of_tuples(d))
print("[{}]".format(f", ".join(f"({k}, {v})" for k,v in dict_to_list_of_tuples(d)) ))