[Python brush questions] - Python entry 09 dictionary (on)

insert image description here

🤵‍♂️ Personal homepage: @North Pole's Sanha personal homepage

👨‍💻 About the author:PythonDomain Rising Star Creator.

📒 Series of columns: " Niuke Question Bank - Python" 🌐Recommend "

Niuke.com "——job search tool|Written Exam Question Bank|interview experience|Internship experience,One-stop solution for job hunting

👉Click the link to register and study

insert image description here


Niu Ke Question Bank " Online Programming - Python "

  pythonThe learning still needs the basic knowledge+Do-it-yourself synchronization. in the case ofpythonIf you are a novice, you need to find a website where you can practice online. I suggest you go to Niuke.com to practice more.

insert image description here


Getting Started with Python: 09 Dictionaries NP67-NP75

insert image description here


NP67 iterate over dictionary

Description
Creates a key-value pair that in turn contains'<': 'less than'and'==': 'equal'dictionaryoperators_dict,

use firstprint()statement print string'Here is the original dict:',

reuseforloop traversal usedsorted()A containing dictionary that the function temporarily sorts in ascending orderoperators_dictFor a list of all keys, useprint()Statement line output similar string'Operator < means less than.'statement;

pair dictionaryoperators_dictAdd key-value pairs'>': 'greater than'back,

output a newline, then useprint()statement print string'The dict was changed to:',

use againforloop traversal usedsorted()A containing dictionary that the function temporarily sorts in ascending orderoperators_dictFor a list of all keys, useprint()Statement line output similar string'Operator < means less than.'statement, confirm the dictionaryoperators_dictA new key-value pair is indeed added.

Input description:
none

Output description:
You can output according to the title description (note that the two output parts need to be separated by a blank line).

Code:

# Create a dictionary operators_dict 
operators_dict =  { '<' :  'less than' , '==' :  'equal' }
 
# First print a line 
print ( 'Here is the original dict:' ) 
# Use the sorted function to sort the list containing all key-value pairs in operators_dict using the for loop 
for key , value in  sorted ( operators_dict . items ( ) ) : 
    # The output looks like String 
    print ( f'Operator { key } means { value } .' )
 
# Add key-value pairs 
operators_dict [ '>' ]  =  'greater than' 
# Output a newline 
print ( ) 
# Print a line of strings 
print ( 'The dict was changed to:' ) 
# Another for loop as above 
for key , value in  sorted ( operators_dict . items ( ) ) : 
    print ( f'Operator { key } means { value } .' )
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

Save the commit:
insert image description here


NP68 Graduate Employment Survey

Description
It's the graduation season again. As the president of the student union of Niuke University, Niu Niu decides to conduct an employment survey on the school's fresh graduates.

He creates a string that in turn contains'Niumei', 'Niu Ke Le', 'GURR'and'GRANDPA'list ofsurvey_list, as a list of surveys; a further list containing key-value pairs in turn is created'Niumei': 'Nowcoder'and'GURR': 'HUAWEI'dictionaryresult_dict, as documented findings.

Please iterate over the listsurvey_list, if the traversed name already appears in the containing dictionaryresult_dictlist of all keys of , then useprint()Statement line output similar string'Hi, Niumei! Thank you for participating in our graduation survey!'statement to express thanks, otherwise useprint()Statement line output similar string'Hi, Niu Ke Le! Could you take part in our graduation survey?'statement to issue an invitation to survey.

Input description:
none

Output description:
You can output according to the title description.

Hi, Niumei! Thank you for participating in our graduation survey!
Hi, Niu Ke Le! Could you take part in our graduation survey?
Hi, GURR! Thank you for participating in our graduation survey!
Hi, LOLO! Could you take part in our graduation survey?
  • 1
  • 2
  • 3
  • 4

Code:

survey_list =  [ 'Niumei' ,  'Niu Ke Le' ,  'GURR' ,  'LOLO' ] 
result_dict =  { 'Niumei' :  'Nowcoder' ,  'GURR' :  'HUAWEI' }
 
for i in survey_list:
    if i in result_dict.keys():
        print(f'Hi, {i}! Thank you for participating in our graduation survey!')
    else:
        print(f'Hi, {i}! Could you take part in our graduation survey?')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Save the commit:
insert image description here


NP69 name and student number

Description
Creates a key-value pair that in turn contains{'name': 'Niuniu'and'Student ID': 1}dictionarymy_dict_1,

Create a sequence that contains key-value pairs{'name': 'Niumei'and'Student ID': 2}dictionarymy_dict_2,

Create a sequence that contains key-value pairs{'name': 'Niu Ke Le'and'Student ID': 3}dictionarymy_dict_3,

Create an empty listdict_list,useappend()method in turn converts the dictionarymy_dict_1、my_dict_2andmy_dict_3add todict_listin, useforloop throughdict_list, for the traversed dictionary, useprint()Statement line output similar string"Niuniu's student id is 1."statement to print the contents of the corresponding dictionary.

Input description:
none

Output description:
You can output according to the title description.

Niuniu's student id  is  1. 
Niumei's student id  is  2. 
Niu Ke Le's student id  is  3.
  • 1
  • 2
  • 3

Code:

my_dict_1 = {'name': 'Niuniu', 'Student ID': 1}
my_dict_2 = {'name': 'Niumei', 'Student ID': 2}
my_dict_3 = {'name': 'Niu Ke Le', 'Student ID': 3}
dict_list = []
dict_list.append(my_dict_1)
dict_list.append(my_dict_2)
dict_list.append(my_dict_3)
 
for i in dict_list:
    key, value = i['name'], i['Student ID']
    print(f"{key}'s student id is {value}.")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Save the commit:
insert image description here


NP70 Capital

Description
Creates a key-value pair that in turn contains'Beijing': {Capital: 'China'}、'Moscow': {Capital: 'Russia'}and'Paris': {Capital: 'France'}dictionarycities_dict, use a for loop to iterate over "usedsorted()A list containing all the keys of the dictionary cities_dict, temporarily sorted by the function in ascending order", for each city name traversed, useprint()Statement line output similar string'Beijing is the capital of China!'statement.

Input description:
none

Output description:
You can output according to the title description.

Beijing is the capital of China!
Moscow is the capital of Russia!
Paris is the capital of France!
  • 1
  • 2
  • 3

Code:

cities_dict = {'Beijing': {'capital': 'China'},
              'Moscow': {'capital': 'Russia'},
              'Paris': {'capital': 'France'}}
 
for city in sorted(cities_dict.keys()):
    city_value = cities_dict[city]
    for item in city_value:
        print(f'{city} is the {item} of {city_value[item]}!')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Save the commit:
insert image description here


NP71 's favorite color

Description
Tuo Ruichi investigated which colors some students in the class liked and created a key-value pair in turn'Allen': ['red', 'blue', 'yellow']、'Tom': ['green', 'white', 'blue']and'Andy': ['black', 'pink']dictionaryresult_dict, as documented findings.

Now Camel Rich wants to look at the dictionaryresult_dictcontent, can you help him?

Use a for loop to iterate over "usesorted()A containing dictionary that the function temporarily sorts in ascending orderresult_dictlist of all keys", for each traversed name, first useprint()Statement line output similar string"Allen's favorite colors are:"statement, and then use a for loop to iterate over the names in the dictionaryresult_dictIn the corresponding list, output the colors in the list in turn.

Input description:
none

Output description:
You can output according to the title description.

Allen's favorite colors are:
red
blue
yellow
Andy's favorite colors are:
black
pink
Tom's favorite colors are:
green
white
blue
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Code:

result_dict =  { 
    'Allen' :  [ 'red' ,  'blue' ,  'yellow' ] , 
    'Tom' :  [ 'green' ,  'white' ,  'blue' ] , 
    'Andy' :  [ 'black' ,  'pink' ' ] 
} 
for i in  sorted ( k for k in result_dict ) : ##List comprehension generates a list of keys 
    print ( "%s's favorite colors are:" % i)
    for x in result_dict[i]:
        print(x)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Save the commit:
insert image description here


Recommended: Niu Ke Question Ba - classic high frequency interview question bank

🌐Job Search Artifact-|Written Exam Question Bank|Interview Experience|Dachang Interview Questions👉Click the link to register and study
insert image description here

Tags: [Python brush questions] - Python entry 09 dictionary (on)

Niu Ke brush questions - Python articles python interview Development language

Related: [Python brush questions] - Python entry 09 dictionary (on)