我想从python字典中输出我的键值对,如下所示:
key1 \t value1
key2 \t value2
我想我可以这样做:
for i in d:
print d.keys(i), d.values(i)
但显然不是这样的,因为keys()和values()不带参数。
我想从python字典中输出我的键值对,如下所示:
key1 \t value1
key2 \t value2
我想我可以这样做:
for i in d:
print d.keys(i), d.values(i)
但显然不是这样的,因为keys()和values()不带参数。
当前回答
字典:
d={'key1':'value1','key2':'value2','key3':'value3'}
另一个单线解决方案:
print(*d.items(), sep='\n')
输出:
('key1', 'value1')
('key2', 'value2')
('key3', 'value3')
(但是,由于之前没有人建议这样做,我怀疑这不是一个好的实践)
其他回答
>>> d={'a':1,'b':2,'c':3}
>>> for kv in d.items():
... print kv[0],'\t',kv[1]
...
a 1
c 3
b 2
或者,对于Python 3:
for k,v in dict.items():
print(k, v)
打印键值对,例如:
players = {
'lebron': 'lakers',
'giannis': 'milwakee bucks',
'durant': 'brooklyn nets',
'kawhi': 'clippers',
}
对于player,在players.items()中的club:
print(f"\n{player.title()} is the leader of {club}")
上面的代码,键值对:
'lebron': 'lakers', - Lebron is key and lakers is value
对于循环-在dictionary.item()中指定键和值:
现在打印(玩家名是俱乐部队长)。
输出为:
#Lebron is the leader of lakers
#Giannis is the leader of milwakee bucks
#Durant is the leader of brooklyn nets
#Kawhi is the leader of clippers
简单介绍一下字典
d={'a':'apple','b':'ball'}
d.keys() # displays all keys in list
['a','b']
d.values() # displays your values in list
['apple','ball']
d.items() # displays your pair tuple of key and value
[('a','apple'),('b','ball')
打印键值,方法一
for x in d.keys():
print(x +" => " + d[x])
另一种方法
for key,value in d.items():
print(key + " => " + value)
你可以使用iter获取密钥
>>> list(iter(d))
['a', 'b']
你可以使用get(key, [value])获取字典key的值:
d.get('a')
'apple'
如果key不存在于字典中,当给出默认值时,将返回value。
d.get('c', 'Cat')
'Cat'
除了已经提到的方法之外。可以使用" viewitems " " viewkeys " " viewvalues "
>>> d = {320: 1, 321: 0, 322: 3}
>>> list(d.viewitems())
[(320, 1), (321, 0), (322, 3)]
>>> list(d.viewkeys())
[320, 321, 322]
>>> list(d.viewvalues())
[1, 0, 3]
Or
>>> list(d.iteritems())
[(320, 1), (321, 0), (322, 3)]
>>> list(d.iterkeys())
[320, 321, 322]
>>> list(d.itervalues())
[1, 0, 3]
或者使用itemgetter
>>> from operator import itemgetter
>>> map(itemgetter(0), dd.items()) #### for keys
['323', '332']
>>> map(itemgetter(1), dd.items()) #### for values
['3323', 232]