将字典追加到元组列表中

时间:2019-04-24 10:14:55

标签: 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', 2), ('z', 3)]

我想得到的时候:

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

2 个答案:

答案 0 :(得分:2)

您的功能就是list(d.items())

>>> list(d.items())
[('x', 1), ('y', 2), ('z', 3)]

以您想要的格式进行打印时,只需使用str.format进行表示即可:

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

答案 1 :(得分:1)

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)) ))