【问题标题】:Python: Transform a Dictionary into a list of listsPython:将字典转换为列表列表
【发布时间】:2011-11-18 04:09:30
【问题描述】:

基本上,我有一个字典,我想将其转换为列表列表(每个组件列表都由字典中的键和值组成)。

我这样做的原因是,我可以使用 for 循环遍历这个新列表,并对键和值执行一些操作。如果有更简单的方法可以做到这一点,我愿意接受建议。

【问题讨论】:

  • 你能提供dict的例子吗?

标签: python list dictionary python-2.7


【解决方案1】:
for key, value in my_dict.iteritems()

这将遍历字典,将每个键存储在key 中,将每个值存储在value 中。 请参阅docs

【讨论】:

  • 在 Python 3 中,请改用 for key, value in iter(my_dict.items())
【解决方案2】:

遍历字典的键和值:

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

【讨论】:

    【解决方案3】:

    我不确定这是否是您所要求的,但这就是我将字典转换为列表的方式,使用它的键作为元组值。

    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) 
    

    【讨论】:

      【解决方案4】:

      这个解决方案怎么样? 无需通过不必要的循环弄脏你的手,更干净更短!!!

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

      【讨论】:

        猜你喜欢
        • 2015-07-23
        • 2022-08-16
        • 1970-01-01
        • 2019-02-10
        • 2015-11-14
        • 2016-10-25
        • 2022-12-04
        • 1970-01-01
        • 2017-04-23
        相关资源
        最近更新 更多