40

I have a dictionary

lang = {'ar':'arabic', 'ur':'urdu','en':'english'}

What I want to do is to delete all the keys except one key. Suppose I want to save only en here. How can I do it ? (pythonic solution)
What I have tried:

In [18]: for k in lang:
   ....:     if k != 'en':
   ....:         del lang_name[k]
   ....

Which gave me the run time error:RuntimeError: dictionary changed size during iteration

4 Answers 4

50

Why don't you just create a new one?

lang = {'en': lang['en']}

Edit: Benchmark between mine and jimifiki's solution:

$ python -m timeit "lang = {'ar':'arabic', 'ur':'urdu','en':'english'}; en_value = lang['en']; lang.clear(); lang['en'] = en_value"
1000000 loops, best of 3: 0.369 usec per loop

$ python -m timeit "lang = {'ar':'arabic', 'ur':'urdu','en':'english'}; lang = {'en': lang['en']}"
1000000 loops, best of 3: 0.319 usec per loop

Edit 2: jimifiki's pointed out in the comments that my solution keeps the original object unchanged.

Sign up to request clarification or add additional context in comments.

8 Comments

Because he wants to modify the dictionary he access HERE as lang and elsewhere as something.attributeName. Maybe.
@jimifiki something.attributeName?
let say he writes lang = someObject.attributeDict; lang = {'en':lang['en']}. Does someObject.attributeDict gets affected by these two lines?
@jimifiki nope, and the OP did not state that he wants to do something like that.
@Marko yep, it's built-in and you can use it from CLI and in Python files: docs.python.org/library/timeit.html
|
36

This is quite fast:

En_Value = lang['en']
lang.clear() 
lang['en'] = En_Value

Comments

11

Iterate over keys() instead:

for k in lang.keys():
    if k != 'en':
        del lang_name[k]

If you're using Python 3 I believe you need to use list(lang.keys()) instead.

Comments

8

pop() it via for loop like this

[s.pop(k) for k in list(s.keys()) if k != 'en']

1 Comment

Calling pop so many times is going to be slow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.