Home > Blockchain >  Avoid creation of extra variable while updating a dictionary
Avoid creation of extra variable while updating a dictionary

Time:09-19

I have a dictionary with one key-value pair,

dct = {'a': 1}

I want to add more key-value pairs to this dictionary, so, I do,

{dct.update(**i) for i in [{'b': 2}, {'c': 3}, {'d': None}] if any(i.values())}

but the IDE starts suggesting to convert this into a variable, and marks the above line with a yellowish background

var = {dct.update(**i) for i in [{'b': 2}, {'c': 3}, {'d': None}] if any(i.values())}

then I add this variable, but it would go unused, and the IDE starts saying unused variable var.

How do I update the dictionary, without IDE having any issues?

CodePudding user response:

Do it in the normal way without using the set-comprehension

for i in [{'b': 2}, {'c': 3}, {'d': None}]:
    if any(i.values()):
        dct.update(**i)

Since you are not using the result set in your code. It's better to keep simple without using any unnecessary comprehensions.

Edit

As mark suggestion, if you have any value 0, you can do like this

for i in [{'b': 2}, {'c': 3}, {'d': None}]:
    if any([v for v in i.values() if v not None])
        dct.update(**i)

CodePudding user response:

If you are thinking about this in terms of key/value pairs, you could turn your dicts into key/value pairs and pass them into update as a flattened list:

dct = {'a': 1}

l = [{'b': 2}, {'c': 3}, {'d': None}]

dct.update((k, v) for d in l for k, v in d.items() if v is not None)

print(dct)
# {'a': 1, 'b': 2, 'c': 3}

This is subtly different from your code of using any(i.values()) in the case where any of these dicts might have more than on value like: {'e':100, 'd': None}. Using the above code, this would add e and not d, but using the any approach you would end up adding the d: None key value pair.

Also, be careful with the construct if any(i.values()) if it possible that any of the values could be 0 to make sure it has the behavior you expect.

CodePudding user response:

have found one way to achieve the same

dct = {i: j for i, j in zip(['a', 'b', 'c', 'd'], [1, 2, 3, None]) if j}

edit

or something like this,

dct = {'a': 1}
dct.update({i: j for i, j in zip(['b', 'c', 'd'], [2, 3, None]) if j})
  • Related