delete all keys except one in dictionary

后端 未结 4 1932
眼角桃花
眼角桃花 2021-02-18 13:22

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.

相关标签:
4条回答
  • 2021-02-18 13:30

    pop() it via for loop like this

    [s.pop(k) for k in list(s.keys()) if k != 'en']
    
    0 讨论(0)
  • 2021-02-18 13:31

    This is quite fast:

    En_Value = lang['en']
    lang.clear() 
    lang['en'] = En_Value
    
    0 讨论(0)
  • 2021-02-18 13:35

    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.

    0 讨论(0)
  • 2021-02-18 13:46

    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.

    0 讨论(0)
提交回复
热议问题