program story

키를 알 수없는 경우 사전에서 항목 제거

inputbox 2020. 8. 3. 08:22
반응형

키를 알 수없는 경우 사전에서 항목 제거


값을 기준으로 사전에서 항목을 제거하는 가장 좋은 방법은 무엇입니까 (예 : 항목의 키를 알 수없는 경우)? 간단한 접근 방식은 다음과 같습니다.

for key, item in some_dict.items():
    if item is item_to_remove:
        del some_dict[key]

더 좋은 방법이 있습니까? 사전을 반복하는 동안 사전에서 돌연변이 (항목 삭제)에 문제가 있습니까?


현재 객체 ID를 테스트하고 있음을 기억하십시오 ( 두 피연산자가 모두 동일한 객체로 메모리에 표시되는 경우 is에만 반환 True됩니다. 이는 항상 두 객체와 비교되는 것은 아닙니다 ==). 의도적으로이 작업을 수행하는 경우 코드를 다음과 같이 다시 작성할 수 있습니다.

some_dict = {key: value for key, value in some_dict.items() 
             if value is not value_to_remove}

그러나 이것은 당신이 원하는 것을하지 않을 수 있습니다 :

>>> some_dict = {1: "Hello", 2: "Goodbye", 3: "You say yes", 4: "I say no"}
>>> value_to_remove = "You say yes"
>>> some_dict = {key: value for key, value in some_dict.items() if value is not value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 3: 'You say yes', 4: 'I say no'}
>>> some_dict = {key: value for key, value in some_dict.items() if value != value_to_remove}
>>> some_dict
{1: 'Hello', 2: 'Goodbye', 4: 'I say no'}

그래서 당신은 아마 !=대신에 원합니다 is not.


dict.pop(key[, default])방법을 사용하면 키를 알고있을 때 항목을 제거 할 수 있습니다. 항목을 제거하면 키에서 값을 반환하고 그렇지 않으면로 전달 된 것을 반환합니다 default. 문서를 참조하십시오 . '

예:

>>> dic = {'a':1, 'b':2}
>>> dic
{'a': 1, 'b': 2}
>>> dic.pop('c', 0)
0
>>> dic.pop('a', 0)
1
>>> dic
{'b': 2}

a = {'name': 'your_name','class': 4}
if 'name' in a: del a['name']

delpop () 의 간단한 비교 :

import timeit
code = """
results = {'A': 1, 'B': 2, 'C': 3}
del results['A']
del results['B']
"""
print timeit.timeit(code, number=100000)
code = """
results = {'A': 1, 'B': 2, 'C': 3}
results.pop('A')
results.pop('B')
"""
print timeit.timeit(code, number=100000)

결과:

0.0329667857143
0.0451040902256

따라서 delpop () 보다 빠릅니다 .


items()목록을 반환하고 반복하는 목록이므로 루프에서 dict를 변경하는 것은 중요하지 않습니다. iteritems()대신 사용 하는 경우 루프에서 dict를 변경하면 문제가 될 수viewitems() 있으며 Python 2.7 에서도 마찬가지입니다 .

값으로 dict에서 항목을 제거하는 더 좋은 방법은 생각할 수 없습니다.


I'd build a list of keys that need removing, then remove them. It's simple, efficient and avoids any problem about simultaneously iterating over and mutating the dict.

keys_to_remove = [key for key, value in some_dict.iteritems()
                  if value == value_to_remove]
for key in keys_to_remove:
    del some_dict[key]

c is the new dictionary, and a is your original dictionary, {'z','w'} are the keys you want to remove from a

c = {key:a[key] for key in a.keys() - {'z', 'w'}}

Also check: https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch01.html


y={'username':'admin','machine':['a','b','c']}
if 'c' in y['machine'] : del y['machine'][y['machine'].index('c')]

There is nothing wrong with deleting items from the dictionary while iterating, as you've proposed. Be careful about multiple threads using the same dictionary at the same time, which may result in a KeyError or other problems.

Of course, see the docs at http://docs.python.org/library/stdtypes.html#typesmapping


This is how I would do it.

for key in some_dict.keys():
    if some_dict[key] == item_to_remove:
        some_dict.pop(key)
        break

참고URL : https://stackoverflow.com/questions/5447494/remove-an-item-from-a-dictionary-when-its-key-is-unknown

반응형