Python: Lists and Dictionaries


We continue to learn the Python programming language Python. We turn to the study of chapter 5 of the book: Michael Dawson “Programming in Python”, 2014 (Michael Dawson “Python Programming for the Absolute Beginner”, 3rd Edition), where we will master lists, list methods and dictionaries.

Lists in Python

Lists are similar to tuples, which we studied in the last chapter. It’s important to remember that, unlike tuples, lists can change. The general principles for working with tuples apply to lists.
General view of the list:

spisok=['one', 'two', 'three','n']

https://skobki.com/en/python-for-loops-constants-slices-tuples-sequences-len-range-in-choice/

As in tuples for a list, you can find out the length using the len() function, you can iterate over values or run a for loop using the in operator, make slices, concatenate, find elements by index.

Changing the list is its main feature when compared with tuples:

  • assign a new value to any element: spisok[0]='кот'
  • assign a new value to a list slice: spisok[0:2]='кот'
  • remove an element from the list: del spisok[0], this will reduce the length of the list;
  • similarly, you can remove a list slice.

List methods – extensions for manipulating lists:

  • add a new element to the end of the list: spisok.append(variable)
  • insert an element at a specific position in the list: spisok.insert(position, value);
  • remove an element from the list: spisok.remove(variable) at the same time, it is important to check if the element being removed is in the list through conditional constructions;
  • list sorting:
    • spisok.sort ascending;
    • spisok.sort(reverse=True) descending;
  • counting the number of times an element is repeated in a list: spisok.count(variable);
  • show the position number in the list where the value first occurs: spisok.index(variable);
  • show the value of a specific list position and remove it from the list:
    • spisok.pop([position]);
    • spisok.pop([]) – show and remove the last element of the list.

Nested lists – a list of data organization, where inside the lists are not individual elements, but lists or tuples. Similarly, you can create a nested tuple.

General view of nested list:

vlojenniy_spisok=['раз', ['кот', 'медведь'], ('сыр', 'колбаса')]

The general form of calling elements of nested lists or tuples:

print(vlojenniy_spisok[3][1])

This entry means: show the first element of the third element of the list: колбаса.

Sequence unpacking – creating a variable for each element from the list / tuple. If there is a list: spisok=['kot','eda'], then its unpacking will look like this: basya, miska = ['kot','eda'].

Dictionaries in Python

Dictionaries are “key” and “value” pairs, similar to regular dictionaries in real life.

General view of the dictionary:

slovar={'key_1':'value_1',
        'key_2':'value_2'}

Create a new value pair in the dictionary or replace an existing one:

slovar[key]=value

Remove a pair of values from a dictionary:

del slovar[key]

To get the value from the dictionary, you need to enter the key: slovar['key_1'], 'value_1' will be displayed. As in the case of removing elements from a list, when retrieving values from a dictionary, it is first best to check if such a key is in the dictionary or not using conditional constructs.

Dictionary methods:

  • get() — retrieves the value by key, and if the key is not present, then returns the value None or any other pre-set value like slovar.get('key_3', 'Default value instead of None');
  • keys() — shows all dictionary keys;
  • values() — shows all dictionary values;
  • items() — shows all key/value pairs as tuples.

Game “What’s in my bag”

Task: Write a text game. The program initially stores a list of things in the user’s bag. Shows the total number of items. Through the index, it makes it possible to check what is under which number. Shows the contents of the slice by two numbers. Next, the user finds the package in the dropbox, which has content that can be seen. Next, the user puts the items from the dropbox into their bag. The user can replace any item from his bag with any other item. Next, the user buys a magic donut with money from the bag. At the end of the program, a thief attacks the user and steals some of the things. What’s left in your bag?

spisok_veshey=['карта','паспорт','ключи','телефон','ручка']
print('В вашей сумке находится:')
for i in spisok_veshey:
    print(i)
print('Общее количество предметов:',len(spisok_veshey))
index=int(input('Введите номер предмета и нажмите Entr \n'))
print('Под номером' ,index, 'находится', spisok_veshey[index])
print('Введите начальный и конечный индекс, чтобы увидеть \
содержимое среза вашей сумки')
index_nach=int(input('Начальный индекс: '))
index_kon=int(input('Конечный индекс: '))
print('В срезе вашей сумки',index_nach,':',index_kon, \
'находится:\n')
for i in spisok_veshey[index_nach:index_kon]:
    print(i)
print('\nВы нашли пакет с вещами в дропбоксе, в котором лежит:\n')
dropbox=['шапочка','варежки','платок']
for i in dropbox:
    print(i)
input('\nЧтобы положить вещи из дропбокс пакета в свою сумку, \
нажмите Entr')
spisok_veshey+=dropbox
print('\nТеперь в вашей сумке лежит:\n')
for i in spisok_veshey:
    print(i)
print('\nВам выпал шанс заменить любой предмет на любой другой')
new_predmet=input('Напишите, что вы хотите добавить в сумку\n')
index_new=int(input('Напишите номер предмета, вместо которого \
вы возьмете новый предмет\n'))
spisok_veshey[index_new]=new_predmet
print('\nТеперь в вашей сумке лежит:\n')
for i in spisok_veshey:
    print(i)
print('\nУ вас осталось немного денег, как раз хватит, чтобы \
купить волшебный пончик!')
input('Нажмите Entr, чтобы купить волшебный пончик')
new_item='волшебный пончик'
spisok_veshey.append(new_item)
print('\nТеперь в вашей сумке лежит:\n')
for i in spisok_veshey:
    print(i)
print('\nВу! На вас напал воришка и украл некоторые вещи!')
del spisok_veshey[:4]
print('\nВ вашей сумке осталось только:\n')
for i in spisok_veshey:
    print(i)

This is what the program itself looks like when it starts:

В вашей сумке находится:
карта
паспорт
ключи
телефон
ручка
Общее количество предметов: 5
Введите номер предмета и нажмите Entr 
4
Под номером 4 находится ручка
Введите начальный и конечный индекс, чтобы увидеть содержимое
среза вашей сумки
Начальный индекс: 1
Конечный индекс: 3
В срезе вашей сумки 1 : 3 находится:

паспорт
ключи

Вы нашли пакет с вещами в дропбоксе, в котором лежит:

шапочка
варежки
платок

Чтобы положить вещи из дропбокс пакета в свою сумку, нажмите Entr

Теперь в вашей сумке лежит:

карта
паспорт
ключи
телефон
ручка
шапочка
варежки
платок

Вам выпал шанс заменить любой предмет на любой другой
Напишите, что вы хотите добавить в сумку
пирожок
Напишите номер предмета, вместо которого вы возьмете новый предмет
4

Теперь в вашей сумке лежит:

карта
паспорт
ключи
телефон
пирожок
шапочка
варежки
платок

У вас осталось немного денег, как раз хватит, чтобы 
купить волшебный пончик!
Нажмите Entr, чтобы купить волшебный пончик

Теперь в вашей сумке лежит:

карта
паспорт
ключи
телефон
пирожок
шапочка
варежки
платок
волшебный пончик

Ву! На вас напал воришка и украл некоторые вещи!

В вашей сумке осталось только:

пирожок
шапочка
варежки
платок
волшебный пончик
>>> 

Ladder games

Task: write a program that shows the top 5 players with their records (do it through a dictionary). The user can also add an entry with a new record, remove any record from the list. If nothing needs to be done, the user can exit the program.

records={'Кот':'6',
         'Медведь':'3',
         'Барсук':'15'}
vibor=None
while vibor!=4:
    vibor=int(input('''"Ладдер игры".
1-Посмотреть ладдер
2-Добавить рекорд
3-Удалить рекорд
4-Выход
Ваш выбор?\n'''))
    if vibor==1:
        for i in records:
            print(i,':',records[i],'\n')
    elif vibor==2:
        new_record_name=input('Введите имя игрока\n')
        new_record_score=input('Введите рекорд\n')
        records[new_record_name]=new_record_score
        for i in records:
            print(i,':',records[i],'\n')
    elif vibor==3:
        delete_record=input('Введите имя игрока, чей \
рекорд нужно удалить.\n')
        if delete_record in records:
            del records[delete_record]
        else:
            print('Игрока с таким именем нет в ладдере')
        for i in records:
            print(i,':',records[i],'\n')
if vibor==4:
    input('Пока пока! Нажмите Entr, чтобы выйти.')

And this is how the program works when you run it:

"Ладдер игры".
1-Посмотреть ладдер
2-Добавить рекорд
3-Удалить рекорд
4-Выход
Ваш выбор?
1
Кот : 6 

Медведь : 3 

Барсук : 15 

"Ладдер игры".
1-Посмотреть ладдер
2-Добавить рекорд
3-Удалить рекорд
4-Выход
Ваш выбор?
2
Введите имя игрока
Ласка
Введите рекорд
9
Кот : 6 

Медведь : 3 

Барсук : 15 

Ласка : 9 

"Ладдер игры".
1-Посмотреть ладдер
2-Добавить рекорд
3-Удалить рекорд
4-Выход
Ваш выбор?
3
Введите имя игрока, чей рекорд нужно удалить.
Кот
Медведь : 3 

Барсук : 15 

Ласка : 9 

"Ладдер игры".
1-Посмотреть ладдер
2-Добавить рекорд
3-Удалить рекорд
4-Выход
Ваш выбор?
4
Пока пока! Нажмите Entr, чтобы выйти.

In the task, it was also necessary to add the ability to sort the results in descending and ascending order. But for this you need to perform the task through lists, and not through dictionaries. Since the dictionary cannot be simply sorted through sort ().

Game “Gallows” Hangman

Task: to write a program – the game “Gallows”, where the computer selects a word unknown to the user, the player must guess this word, assuming the presence of different letters in the word. The player suggests a letter, if there is no such letter in the word, then the computer draws the image. If in a limited number of attempts the player does not guess the whole word, then he will lose.

SLOVA=('кот','мяв','хрю')
import random
zag_slovo=random.choice(SLOVA)
otgad_slovo='*'*len(zag_slovo)
oshibki=0
isp_bukvi=[]
CAT=('''
.
▕▔▔╲▂▂▂▂▂╱▔▔▏┈┈┈
▕╲╱╱┋┋┋┋┋╲╲╱▏▕▔▏
''',
'''
.
▕▔▔╲▂▂▂▂▂╱▔▔▏┈┈┈
▕╲╱╱┋┋┋┋┋╲╲╱▏▕▔▏
┉╲╱╭▆╮┋╭▆╮╲╱┉┉╲╲
┉▕╲┉┉┉▅┉┉┉╱▏┉┉▕▕
''',
'''
.
▕▔▔╲▂▂▂▂▂╱▔▔▏┈┈┈
▕╲╱╱┋┋┋┋┋╲╲╱▏▕▔▏
┉╲╱╭▆╮┋╭▆╮╲╱┉┉╲╲
┉▕╲┉┉┉▅┉┉┉╱▏┉┉▕▕
┉▕┉▔▔╰┻╯▔▔┉▏┉┉╱╱
┉┈╲▂▂▂▂▂▂▂╱╲┉▕▕┉
┉┉╱╰╰╰╯╯╯╮╮╮╲╱╱┉
''')
MAX_OSHIBKI=len(CAT)-1
print('Игра "Виселица"')
while oshibki<MAX_OSHIBKI and otgad_slovo!=zag_slovo:
    print (CAT[oshibki])
    print('Загаданное слово:', otgad_slovo)
    print('Использованные варианты букв:', isp_bukvi)
    otgadka=input('Угадайте букву: ')
    otgadka=otgadka.lower()
    while otgadka in isp_bukvi:
        print('Вы уже предлагали букву',otgadka)
        otgadka=input('Угадайте букву: ')
        otgadka=otgadka.lower()
    isp_bukvi.append(otgadka)
    if otgadka in zag_slovo:
        print('Ура! Буква',otgadka,'есть в слове:')
        new=''
        for i in range(len(zag_slovo)):
            if otgadka == zag_slovo[i]:
                new+=otgadka
            else:
                new+=otgad_slovo[i]
        otgad_slovo=new
    else:
        print('Ошибочка! Буквы',otgadka,'нет в слове.')
        oshibki+=1
if oshibki == MAX_OSHIBKI:
    print(CAT[oshibki])
    print('Вы не успели отгадать слово и стали котом')
else:
    print('Ура! Вы угадали! Это слово:',zag_slovo)
input('Нажмите Entr для выхода из игры.')

А вот так выглядит игра “Виселица”, когда запускаешь программу:

Игра "Виселица"

.
▕▔▔╲▂▂▂▂▂╱▔▔▏┈┈┈
▕╲╱╱┋┋┋┋┋╲╲╱▏▕▔▏

Загаданное слово: ***
Использованные варианты букв: []
Угадайте букву: р
Ура! Буква р есть в слове:

.
▕▔▔╲▂▂▂▂▂╱▔▔▏┈┈┈
▕╲╱╱┋┋┋┋┋╲╲╱▏▕▔▏

Загаданное слово: *р*
Использованные варианты букв: ['р']
Угадайте букву: а
Ошибочка! Буквы а нет в слове.

.
▕▔▔╲▂▂▂▂▂╱▔▔▏┈┈┈
▕╲╱╱┋┋┋┋┋╲╲╱▏▕▔▏
┉╲╱╭▆╮┋╭▆╮╲╱┉┉╲╲
┉▕╲┉┉┉▅┉┉┉╱▏┉┉▕▕

Загаданное слово: *р*
Использованные варианты букв: ['р', 'а']
Угадайте букву: ю
Ура! Буква ю есть в слове:

.
▕▔▔╲▂▂▂▂▂╱▔▔▏┈┈┈
▕╲╱╱┋┋┋┋┋╲╲╱▏▕▔▏
┉╲╱╭▆╮┋╭▆╮╲╱┉┉╲╲
┉▕╲┉┉┉▅┉┉┉╱▏┉┉▕▕

Загаданное слово: *рю
Использованные варианты букв: ['р', 'а', 'ю']
Угадайте букву: х
Ура! Буква х есть в слове:
Ура! Вы угадали! Это слово: хрю
Нажмите Entr для выхода из игры.
>>> 

 


This entry was posted in Python (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.