사전의 길이를 계산하려면 Python 내장 len() 메서드를 사용할 수 있습니다. len() 메소드는 키 개수를 반환합니다. 파이썬 사전 .
Python Dict len() 구문
통사론: len(딕셔너리)
반품: 문자열의 길이인 정수를 반환합니다.
Name:Steve Age:30 Designation:Programmer>
사전의 길이를 찾는 기본 예
파이썬3
base64 자바스크립트 디코드
dict1>=>{>'Name'>:>'Steve'>,>'Age'>:>30>,>'Designation'>:>'Programmer'>}> print>(>'Dictionary:'>, dict1)> print>(>'Length of dictionary:'>,>len>(dict1))> |
>
>
산출:
Dictionary: {'Name': 'Steve', 'Age': 30, 'Designation': 'Programmer'} Length of dictionary: 3> 중첩된 사전의 길이 찾기
개인에 대해 다음 세부 사항을 고려하십시오.
Name:Steve Age:30 Designation:Programmer address: Street:Brigade Road City:Bangalore Country:India>
중첩된 사전의 길이를 찾으려고 할 때 문제가 발생합니다.
파이썬3
# A nested dictionary> dict2>=> {># outer dictionary> >'Name'>:>'Steve'>,> >'Age'>:>30>,> >'Designation'>:>'Programmer'>,> >'address'>: {># inner dictionary> >'Street'>:>'Brigade Road'>,> >'City'>:>'Bangalore'>,> >'Country'>:>'India'> >}> }> print>(>'len() method :'>,>len>(dict2))> print>(>'len() method with keys() :'>,>len>(dict2.keys()))> print>(>'len() method with values():'>,>len>(dict2.values()))> |
>
>
산출:
len() 메서드(key() 포함): 4
값()이 있는 len() 메서드: 4
여기서는 어떤 방법을 적용하더라도 '4'만 출력됩니다. 하지만 실제 항목 수는 '7'개입니다. 키는 이름, 나이, 명칭, 주소, 거리, 도시, 국가입니다. 이 방법은 키 중 하나의 값인 외부 사전을 단일 값으로 간주합니다.
이 문제를 극복하려면 내부 사전의 길이를 외부 사전에 명시적으로 추가해야 합니다. 아래와 같이 코딩할 수 있습니다.
파이썬3
# A nested dictionary> dict2>=>{> >'Name'>:>'Steve'>,> >'Age'>:>30>,> >'Designation'>:>'Programmer'>,> >'address'>:> >{> >'Street'>:>'Brigade Road'>,> >'City'>:>'Bangalore'>,> >'Country'>:>'India'> >}> >}> # total length = length of outer dict +> # length of inner dict> length>=> len>(dict2)>+>len>(dict2[>'address'>])> print>(>'The length of the nested dictionary is:'>, length)> |
>
>
산출:
The length of the nested dictionary is: 7>
이제 잘 작동합니다!!! 그런데 매번 내부 사전의 길이를 추가하도록 명시적으로 프로그래밍하는 것이 가능합니까? 사전에 내부 사전이 몇 개 있는지 모른다면 어떻게 될까요? 이제 다음 세부 사항을 고려하십시오.
Name: first name:Steve last name:Jobs Age:30 Designation:Programmer address: Street:Brigade Road City:Bangalore Country:India>
여기에는 두 개의 내부 사전이 있습니다. 매번 내부 사전의 길이를 명시적으로 추가하는 것은 최적화된 방법이 아닙니다. isinstance()와 len() 메소드를 결합하여 이 문제를 해결할 수 있습니다. 아이디어는 먼저 전체 사전의 길이를 변수에 저장하는 것입니다. (여기서 '길이'라고 말하세요) . 그런 다음 사전의 모든 값()을 반복하고 그것이 dict의 인스턴스인지 확인합니다. 만약에 '진실' 그런 다음 해당 내부 사전의 길이를 찾아 변수에 추가합니다. 길이 . 이러한 방식으로 중첩된 사전의 전체 길이를 찾을 수 있습니다.
예 1: for 루프를 사용하여 동적으로 중첩된 사전의 길이 찾기:
값이 다시 사전인 사전에 더 많은 키가 있는 경우. 그런 다음 각 키 값의 유형을 확인해야 합니다. 사전인 경우 값에 대해 len()을 사용하고 해당 값을 외부 사전의 길이에 추가합니다.
파이썬3
# nested dictionary> dict2>=>{> >'Name'>:> >{> >'first_name'>:>'Steve'>,> >'Last_name'>:>'Jobs'> >},> >'Age'>:>30>,> >'Designation'>:>'Programmer'>,> >'address'>:> >{> >'Street'>:>'Rockins Road'>,> >'City'>:>'Bangalore'>,> >'Country'>:>'India'> >}> >}> # storing the outer dictionary length> length>=> len>(dict2)> # iterating to find the length> # of all inner dictionaries> for> i>in> dict2.values():> ># checking whether the value is a dictionary> >if> isinstance>(i,>dict>):> >length>+>=> len>(i)> > print>(>'The length of the dictionary is'>, length)> |
>
>
산출:
The length of the dictionary is 9>
메모: 이 접근 방식은 사전 중첩이 최대 2개 수준인 경우에만 작동합니다.
사전이 아래와 같이 더 깊게 중첩된 경우:
Name: first name:Steve last name:Jobs Age:30 Designation:Programmer address: Street: St_number:4 St_name:Brigade Road City:Bangalore Country:India>
예 2: 재귀를 사용하여 중첩된 사전의 길이 찾기:
여기서 우리는 재귀 함수 count_nested_len()을 사용하여 각 사전의 길이를 계산하고, 사전의 키를 반복하고, 값이 사전이 되자마자 해당 사전을 기각합니다.
파이썬3
산술 논리 장치
# nested dictionary> dict2>=>{> >'Name'>:> >{> >'first_name'>:>'Steve'>,> >'Last_name'>:>'Jobs'> >},> >'Age'>:>30>,> >'Designation'>:>'Programmer'>,> >'address'>:> >{> >'Street'>:> >{> >'st_number'>:>4>,> >'st_name'>:>'Rockins Road'> >},> >'City'>:>'Bangalore'>,> >'Country'>:>'India'> >}> >}> # we use recursive function to count> # length of nested dictionaries> def> count_nested_len(d):> >length>=> len>(d)> >for> key, value>in> d.items():> >if> isinstance>(value,>dict>):> >length>+>=> count_nested_len(value)> >return> length> print>(>'Nested dictionary length:'>,> >count_nested_len(dict2))> |
>
>
산출:
Nested dictionary length: 11>
접근 방식 3: 사전 이해 사용
파이썬3
# 중첩된 사전
dict2 ={
'이름':
{
'이름':'스티브',
'성':'작업'
},
'연령':30,
'지정':'프로그래머',
'주소':
{
'거리':
{
'st_번호':4,
'st_name':'로킨스 로드'
},
'도시': '방갈로르',
'국가':'인도'
}
}
# 사전 이해를 사용하여 중첩된 사전의 길이를 찾습니다.
길이 = len({k: v for k, v in dict2.items()})
print(사전의 길이는, 길이)
#이 코드는 Edula Vinay Kumar Reddy가 제공했습니다.
방법 4: sum() 함수와 함께 생성기 표현식을 사용합니다.
접근하다:
생성기 표현식은 1의 시퀀스를 만드는 데 사용됩니다. 여기서 각 1은 사전의 키에 해당합니다. 그런 다음 sum() 함수를 사용하여 1을 더해 사전의 길이를 구합니다.
연산:
1. 사전의 각 키에 대해 1의 시퀀스를 생성하는 생성기 표현식을 만듭니다.
2. sum() 함수를 사용하여 시퀀스의 1을 더합니다.
3. 사전의 길이를 나타내는 합계를 반환합니다.
파이썬3
dict1>=> {>'Name'>:>'Steve'>,>'Age'>:>30>,>'Designation'>:>'Programmer'>}> length>=> sum>(>1> for> key>in> dict1)> print>(length)> |
>
>산출
3>
이 접근 방식의 시간 복잡도는 O(n)입니다. 여기서 n은 사전의 키 수입니다.
이 접근 방식의 공간 복잡도는 O(1)입니다.