Python从单元素字典中获取key和value的方法与代码实例

2018-12-3116:27:43后端程序开发Comments1,598 views字数 238阅读模式

写代码很多时候会遇到这么一种情况:在python的字典中只有一个key/value键值对,想要获取其中的这一个元素还要写个for循环获取。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9161.html

网上搜了一下,发现还有很多简单的方法:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9161.html

方法一文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9161.html

d = {'name':'haohao'}
(key, value), = d.items()

方法二文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9161.html

d = {'name':'haohao'}
key = list(d)[0]
value = list(d.values())[0]

方法三文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9161.html

d = {'name':'haohao'}
key, = d
value, = d.values()
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9161.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/9161.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定