2011-09-15 21 views
4

基本的には、辞書のキーと値からなる各コンポーネントリストをリストのリストに変換する辞書があります。Python:辞書をリストのリストに変換する

私がこれをやっている理由は、この新しいリストをforループで繰り返し、キーと値の両方で何かを行うことができるようにするためです。これを行う簡単な方法がある場合は、私は提案に公開しています。

+0

「dict」の例を挙げることはできますか? –

答えて

12
for key, value in my_dict.iteritems() 

これはkeyにおける各キーとvalueの各値を記憶し、辞書を反復します。 docsを参照してください。

3

辞書のキーと値を反復処理するために:

for key, value in D.iteritems(): 
    # do something with them 
0

私はこれがあなたが求めているものであるのかはわからないが、これは、私のようにそのキーを使用して、リストの中に辞書を有効にする方法をありますタプルされた値。

new_list = [] 
dict = {test:1, test:2, test:3} 
for key, value in dict.iteritems(): 
    new_list.append((key, value)) 

ここで私はあなたが欲しいものに非常に類似した何かをしています。

if str(vm_mor) == vm['config.annotation']: 
    annotation= pickle.load(open(str(vm_mor), "rb")) 
    print annotation 

    sql_check_exist = '''select a.vm_mor, b.license_id, c.product from vms a , vm_licenses b, licenses c where a.vm_id = b.vm_id and b.license_id = c.license_id and a.vm_mor = '%s' ''' % str(vm_mor) 
    cursor_exist.execute(sql_check_exist) 
    database_license = [] 

    for vm_mor, license_id, product in cursor_exist: 
     database_license.append((product,license_id)) 

    checklist_database_license = [int(i[1]) for i in database_license] #make a list of 2nd element of all the tuples in the database_license list 
    check_me = annotation['license'] 

    for product, license_id in check_me: 
     if license_id in checklist_database_license: 
      print "do nothing" 
     else: 
      del annotation['license'] 
      annotation['license'] = database_license 
      change = True 

    if change == True:   
     change_annotation(vm_mor, annotation) 
     change = False  

else: 
    print vm['config.name'] 
    pickle_mor(vm_mor,vm) 
5

このソリューションについてはどうですか? 不必要なループ、クリーナー、ショートで手を汚す必要はありません!

d = { 'a': 1, 'b': 2, 'c': 3 } 
map(list, d.items()) 
[['a', 1], ['c', 3], ['b', 2]] 
+0

これは受け入れられた回答であったはずです。 –

関連する問題