简体   繁体   中英

Replace values in a dictionary with the values from the list

I am trying to replace the values in my dictionary with values from a list.

I have:

list1 = ['10 2', '8 6']

d = {'0.25': ['11 3', '9 1'], '0.75': ['3 9'], '0.5': ['10 12', '6 0'], '0.0': ['1 8']}

and I would like my dictionary to look like:

dFinal = {'0.25': ['10 2'], '0.75': ['3 9'], '0.5': ['8 6'], '0.0': ['1 8']}

Generally, if a value for my key is a list with two items, I would like to replace that value with the particular item from list1. I would like the method to work for list1 with any number of items and it seems to be my problem.

So far I got:

for key in d:
    if len(d[key]) == 2:
        d[key] = list1[0]

but it only replaces everything with one value and I would like to avoid calling static indexes as the length of my list1 can vary... Am I missing a loop of some-kind?

Cheers!

You can add a simple counter (a new variable).

i = 0
for key in d:
    #check if we're not out of bounds
    if i >= len(list1):
        break
    if len(d[key]) == 2:
        d[key] = [list1[i]]
        i+=1

This should do the trick:

replace = [x for x in d if len(d[x]) == 2]
for (i, x) in enumerate(replace):
   d[x] = [list1[i]]

However, I think you need to be very careful here as a dictionary is not an ordered list, so if the elements in list1 are going to be mapped correctly, you'll need to check that Python hasn't shuffled the dictionary at all. The code above will work fine with the example provided, but the robustness of any solution to this formulation is going to depend on what you're doing with your dictionary (and list1 ) elsewhere.

Sorry to be finicky, but I've had problems with Python shuffling dictionaries in the background and it ruining my algorithm before.

list1 = ['10 2', '8 6']
d = {'0.25': ['11 3', '9 1'], '0.75': ['3 9'], '0.5': ['10 12', '6 0'], '0.0': ['1 8']}
iter_list = iter(list1)
for key, value in d.items():
    if len(value) == 2:
        try:
            d[key] = [next(iter_list)]
        except StopIteration:
            break

Result:

{'0.0': ['1 8'], '0.25': ['10 2'], '0.5': ['8 6'], '0.75': ['3 9']}

You can use zip()

>>> list1 = ['10 2', '8 6']
>>> for x, y in zip(list1,d.items()):
...     d[y[0]] = [x]
... 
>>> print d
{'0.25': ['10 2'], '0.5': ['8 6'], '0.75': ['3 9'], '0.0': ['1 8']}

Explanation:

zip(list1,d.items())

Returns:

[('10 2', ('0.25', ['10 2'])), ('8 6', ('0.5', ['8 6']))]

It only gets the values of keys which is a length of two, as that is what zip() does. Then I iterate through the list, changing the values of keys in the dictionary corresponding to the first value in the zip(list1,d.items()) .

Using filter, zip and the update function you can achieve this in a quiete simple way:

list1 = ['10 2', '8 6']

d = {'0.25': ['11 3', '9 1'], '0.75': ['3 9'], '0.5': ['10 12', '6 0'], '0.0': ['1 8']}

print d
target_keys = filter(lambda x: len(d[x]) == 2, d.keys())
new_list = zip(target_keys, list1)
new_dict = dict(new_list)
d.update(new_dict)
print d

The nice thing about zip is that it takes only the indexes that exists on both lists so you don't have to worry about out of range errors.

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