Pythonでdictからキーと値のタプルのリストを取得するにはどうすればよいですか?
76091 次
5 に答える
89
Python 2.x のみ (Alex に感謝):
yourdict = {}
# ...
items = yourdict.items()
詳細については、 http://docs.python.org/library/stdtypes.html#dict.itemsを参照してください。
Python 3.x のみの場合 ( Alex の回答から取得):
yourdict = {}
# ...
items = list(yourdict.items())
于 2009-08-18T19:42:48.803 に答える
9
タプルのリストの場合:
my_dict.items()
ただし、アイテムを繰り返し処理するdict.iteritems()
だけの場合は、すべてのアイテムを一度に返すのではなく、一度に 1 つのアイテムのみを返すため、メモリ効率の良いを使用することをお勧めします。
for key,value in my_dict.iteritems():
#do stuff
于 2009-08-18T19:45:09.937 に答える
6
Python2.*
ではthedict.items()
、@Andrew の回答のように。Python3.*
ではlist(thedict.items())
(items
リストではなく反復可能なビューがあるだけなlist
ので、正確にリストが必要な場合は明示的に呼び出す必要があります)。
于 2009-08-18T19:45:45.413 に答える
6
dict
からへの変換list
は Python で簡単にできます。3 つの例:
d = {'a': 'Arthur', 'b': 'Belling'}
d.items() [('a', 'Arthur'), ('b', 'Belling')]
d.keys() ['a', 'b']
d.values() ['Arthur', 'Belling']
前の回答Converting Python Dictionary to Listに見られるように。
于 2012-06-27T16:40:53.983 に答える
-2
Python > 2.5 の場合:
a = {'1' : 10, '2' : 20 }
list(a.itervalues())
于 2011-03-18T13:51:19.887 に答える