简体   繁体   中英

Iteration of dict with key and List of values in python

I have dictionary in python with key as 'string' and value as list of integers. Iterating the dict with key and value and if delete the value in the list if it does not meet some conditions. Iteration does not properly.

For example,

my_dict = {"emp_id":[100,200]}

for emp,ids in my_dict.iteritems():
    print "Emp :",emp
    for id in ids:
        print "Id :",id
        if not id > 1000:
            my_dict.get(emp).remove(id)
            continue

Output :

Emp : emp_id
Id : 100

It does not iterate the second value (200) in the list. Not sure what could be problem. Is it due the removal of value in the dict.

How to resolve this. Do we need to do copy to another object and remove from it.

you should not remove element during iteration

my_dict={'emp_id': [100, 200, 10000]}
new_dict={ emp:[ele for ele in ids if ele <= 1000] for emp,ids in my_dict.iteritems() }
{'emp_id': [100, 200]}

You cannot reliably modify a list over which you are iterating. Simply filter the list, then replace it with the filtered copy.

for emp, ids in mydict.iteritems():
    print "Emp:", emp
    new_ids = []
    for id in ids:
        print "Id", id
        if id > 1000:
            new_ids.append(id)
    my_dict[emp] = new_ids

If you aren't printing each id as you see it, you can replace the inner loop with a single call to filter :

for emp, ids in my_dict.iteritems():
    my_dict[emp] = [id for id in ids if id > 1000]
    # my_dict[emp] = filter(lambda x: x > 1000, ids)

You could even rebuild the entire dict from scratch:

my_dict = {emp: [id for id in ids if id > 1000] for emp, ids in my_dict.iteritems()}

It's not good to modify my_dict during iteration.

If you want to just print: not (id > 1000), then remove my_dict.get(emp).remove(id).

Otherwise, remove first then print.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM