python - How can I populate a dictionary with an enumerated list? -


i have following dictionary, keys integers , values floats:

foo = {1:0.001,2:2.097,3:1.093,4:5.246} 

this dictionary has keys 1, 2, 3 , 4.

now, remove key '2':

foo = {1:0.001,3:1.093,4:5.246} 

i have keys 1, 3 , 4 left. want these keys called 1, 2 , 3.

the function 'enumerate' allows me list [1,2,3]:

some_list = [] k,v in foo.items():     some_list.append(k) num_list = list(enumerate(some_list, start=1)) 

next, try populate dictionary these new keys , old values:

new_foo = {} in num_list:     value in foo.itervalues():         new_foo[i[0]] = value 

however, new_foo contains following values:

{1: 5.246, 2: 5.246, 3: 5.246} 

so every value replaced last value of 'foo'. think problem comes design of loop, don't know how solve this. tips?

agreeing other responses list implements behavior describe, , more appropriate, suggest answer anyway.

the problem code way using data structures. enumerate items left in dictionary:

new_foo = {} key, (old_key, value) in enumerate( sorted( foo.items() ) ):     key = key+1  # adjust 1-based     new_foo[key] = value 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -