python字典转化成列表函数_将字典转换为Python中的元组列表

从一种收集类型转换为另一种收集类型在python中非常常见。根据数据处理的需要,我们可能必须将字典中存在的键值对转换为代表列表中元组的对。在本文中,我们将看到实现这一目标的方法。

这是一种简单的方法,我们只考虑

示例Adict = {30:'Mon',11:'Tue',19:'Fri'}

# Given dictionary

print("The given dictionary: ",Adict)

# Using in

Alist = [(key, val) for key, val in Adict.items()]

# Result

print("The list of tuples: ",Alist)

输出结果

运行上面的代码给我们以下结果-The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}

The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]

带拉链

zip函数将传递给它的项目组合为参数。因此,我们将字典的键和值作为zip函数的参数,并将结果放在list函数下。键值对成为列表的元组。

示例Adict = {30:'Mon',11:'Tue',19:'Fri'}

# Given dictionary

print("The given dictionary: ",Adict)

# Using zip

Alist = list(zip(Adict.keys(), Adict.values()))

# Result

print("The list of tuples: ",Alist)

输出结果

运行上面的代码给我们以下结果-The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}

The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]

带附加

在这种方法中,我们采用一个空列表并将每个键值对附加为元组。for循环用于将键值对转换为元组。

示例Adict = {30:'Mon',11:'Tue',19:'Fri'}

# Given dictionary

print("The given dictionary: ",Adict)

Alist = []

# Uisng append

for x in Adict:

k = (x, Adict[x])

Alist.append(k)

# Result

print("The list of tuples: ",Alist)

输出结果

运行上面的代码给我们以下结果-The given dictionary: {30: 'Mon', 11: 'Tue', 19: 'Fri'}

The list of tuples: [(30, 'Mon'), (11, 'Tue'), (19, 'Fri')]

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值