logo

Python에서 사전에 사용자 입력을 추가하는 방법

Python에서 사전은 정렬되지 않은 키-값 쌍 모음을 나타내는 내장 데이터 유형입니다. 사전은 때때로 dict라고 불립니다. 키를 기반으로 데이터를 효율적으로 저장하고 검색하는 방법을 제공합니다. Python의 사전은 중괄호 {}를 사용하여 정의됩니다. 이 기사에서는 Python의 사전에 사용자 입력을 추가합니다.

Python의 사전에 사용자 입력 추가

다음은 사용자 입력을 추가할 수 있는 몇 가지 방법입니다. 사전 ~에 파이썬 :

  • 루프 사용하기 입력() 기능
  • input() 함수로 사전 이해 사용하기
  • update() 메소드 사용

input() 함수와 함께 루프 사용하기

이 예에서는 추가하려는 사전 항목 수를 입력하라는 메시지가 사용자에게 표시됩니다. for 루프는 지정된 숫자를 반복하여 사용자로부터 키-값 쌍을 수집하고 입력으로 사전(`user_dict`)을 업데이트합니다. 마지막으로 추가된 사용자 입력을 반영하여 결과 사전이 인쇄됩니다.

파이썬3




user_dict>=> {}> num_entries>=> int>(>input>(>'Enter the number of entries you want to add: '>))> for> i>in> range>(num_entries):> >key>=> input>(>'Enter key: '>)> >value>=> input>(>'Enter value: '>)> >user_dict[key]>=> value> print>(>'Dictionary after adding user input:'>, user_dict)>

>

>

산출:

Enter the number of entries you want to add: 4 Enter key: adarsh Enter value: 12 Enter key: raj Enter value: 10 Enter key: Aditya Enter value: 10 Enter key: Anish Enter value: 11 Dictionary after adding user input: {'adarsh': '12', 'raj': '10', 'Aditya': '10', 'Anish': '11'}>

input() 함수로 사전 이해 사용하기

이 예에서는 추가하려는 사전 항목 수를 입력하라는 메시지가 사용자에게 표시됩니다. 사용하여 사전 이해 , 프로그램은 간결한 방식으로 사용자로부터 키-값 쌍을 수집합니다. 추가된 사용자 입력을 반영하여 결과 사전(`user_dict`)이 인쇄됩니다.

파이썬3




num_entries>=> int>(>input>(>'Enter the number of entries you want to add: '>))> user_dict>=> {>input>(f>'Enter key {i+1}: '>):>input>(f>'Enter value {i+1}: '>)>for> i>in> range>(num_entries)}> print>(>'Dictionary after adding user input:'>, user_dict)>

>

>

산출:

Enter the number of entries you want to add: 2 Enter key 1: Adarsh Enter value 1: 12 Enter key 2: Raj Enter value 2: 10 Dictionary after adding user input: {'Adarsh': '12', 'Raj': '10'}>

update() 메소드 사용

이 예에서는 추가하려는 사전 항목 수를 입력하라는 메시지가 사용자에게 표시됩니다. for 루프를 통해 사용자로부터 키-값 쌍이 수집되고 ` 업데이트() ` 메소드는 이러한 쌍을 기존 사전(`user_dict`)에 추가하는 데 사용됩니다. 마지막으로 추가된 사용자 입력을 반영하여 결과 사전이 인쇄됩니다.

파이썬3




Java의 arraylist 정렬
user_dict>=> {}> num_entries>=> int>(>input>(>'Enter the number of entries you want to add: '>))> for> i>in> range>(num_entries):> >key>=> input>(>'Enter key: '>)> >value>=> input>(>'Enter value: '>)> >user_dict.update({key: value})> print>(>'Dictionary after adding user input:'>, user_dict)>

>

>

산출:

Enter the number of entries you want to add: 2 Enter key: Ram Enter value: 11 Enter key: raj Enter value: 122 Dictionary after adding user input: {'Ram': '11', 'raj': '122'}>