python打印字典的键值,如何在python中打印字典的键值对

I want to output my key value pairs from a python dictionary as such:

key1 \t value1

key2 \t value2

I thought I could maybe do it like this:

for i in d:

print d.keys(i), d.values(i)

but obviously that's not how it goes as the keys() and values() don't take an argument...

Thanks.

解决方案

Your existing code just needs a little tweak. i is the key, so you would just need to use it:

for i in d:

print i, d[i]

You can also get an iterator that contains both keys and values. In Python 2, d.items() returns a list of (key, value) tuples, while d.iteritems() returns an iterator that provides the same:

for k, v in d.iteritems():

print k, v

In Python 3, d.items() returns the iterator; to get a list, you need to pass the iterator to list() yourself.

for k, v in d.items():

print(k, v)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值