Manuel Semeco
Manuel Semeco

Reputation: 53

how to delete and add multiple items without iterating a dictionary in python 3.7x?

I wonder if a existing dictionary instance can add and/or delete multiple items without using iterations. I mean something like this.

supposition:(it actually doesn't work)

D = {"key1":"value1", "key2":"value2", "key3":"value3"}
tags = ["key1","key2"]
D.pop(tags)
print(D)
{"key3":"value3"}

Thank you in advance.

Upvotes: 1

Views: 357

Answers (3)

John Greenfield
John Greenfield

Reputation: 143

If all you're wanting to do is show the dictionary where key from list is not present, why not just create a new dic:

D = {"key1":"value1", "key2":"value2", "key3":"value3"}
tags=["key1", "key2"]

dict = {key:value for key, value in D.items() if key not in tags}

print(dict)

Upvotes: -1

Blckknght
Blckknght

Reputation: 104752

If you don't actually need to avoid iteration, but rather just want to do the transformation of the dictionary in an expression, rather than a statement, you could use a dictionary comprehension to create a new dictionary containing only the keys (and the associated values) that don't match your list of things to remove:

D = {key: value for key, value in D.items() if key not in tags}

Unfortunately, this doesn't modify D in place, so if you need to change the value referenced through some other variable this won't help you (and you'd need to do an explicit loop). Note that if you don't care about the values being removed, you probably should use del D[key] instead of D.pop(key).

Upvotes: 0

Kevin Mayo
Kevin Mayo

Reputation: 1159

If so, you could iterate a list instead of iterate the full dict:

D = {"key1":"value1", "key2":"value2", "key3":"value3"}
for i in ["key1", "key2"]:
    D.pop(i)

print(D)

Upvotes: 2

Related Questions