값이 일치하는 사전을 제거해야 하는 경우 사전 이해를 사용합니다.
아래는 동일한 데모입니다 -
예시
my_dict_1 = [{'Hi': 32, "there": 32, "Will":19},{'Hi': 19, "there": 100, "Will": 13}, {'Hi': 72, "there": 19, "Will": 72}]
print("The first dictionary is : ")
print(my_dict_1)
my_dict_2 = [{'Hi': 72, "Will": 19}, {"Will": 13, "Hi": 19}]
print("The second dictionary is : ")
print(my_dict_2)
K = "Hi"
print("The value of K is ")
print(K)
temp = { element[K] for element in my_dict_2}
my_result = [element for element in my_dict_1 if element[K] not in temp]
print("The result is : " )
print(my_result) 출력
The first dictionary is :
[{'Hi': 32, 'there': 32, 'Will': 19}, {'Hi': 19, 'there': 100, 'Will': 13}, {'Hi': 72, 'there': 19, 'Will': 72}]
The second dictionary is :
[{'Hi': 72, 'Will': 19}, {'Will': 13, 'Hi': 19}]
The value of K is
Hi
The result is :
[{'Hi': 32, 'there': 32, 'Will': 19}] 설명
-
두 개의 사전이 정의되어 콘솔에 표시됩니다.
-
K 값이 정의되어 콘솔에 표시됩니다.
-
두 번째 사전은 반복되고 요소는 K로 확인되고 임시 변수 'temp'에 저장됩니다.
-
첫 번째 사전이 반복되고 그 안에 있는 요소가 임시 변수 'temp'로 검사되어 변수에 할당됩니다.
-
이 결과는 변수에 할당됩니다.
-
콘솔에 표시되는 출력입니다.