Basically, I have a dictionary that I want to transform into a list of lists (with each component list consisting of the key and value from the dictionary).
The reason I am doing this is so that I can iterate 开发者_如何学Gothrough this new list with a for loop and do something with both the key and the value. If there is an easier way to do this, I am open to suggestions.
How about this solution ? No need to make your hand dirty by unnecessary looping through, cleaner and shorter !!!
d = { 'a': 1, 'b': 2, 'c': 3 }
list(map(list, d.items()))
[['a', 1], ['c', 3], ['b', 2]]
for key, value in my_dict.iteritems()
This will iterate through the dictionary, storing each key in key
and each value in value
.
See the docs.
to iterate over a dictionary's keys and values:
for key, value in D.iteritems():
# do something with them
I'm not sure if this is what you're asking for but this is how I would turn a dictionary into a list using its key as a tupled value.
new_list = []
dict = {test:1, test:2, test:3}
for key, value in dict.iteritems():
new_list.append((key, value))
Here is where I am doing something very similar to what you want.
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)
精彩评论