Python Programming Fundamentals: Strings and Common Data Structures (Lists, Tuples, Sets, Dictionaries)

[[List]] []
[[Tuple]] ()
[[Set]] {}
[[Dictionary]] {'':}

Dictionary

# Literal syntax for creating a dictionary  
scores = {'Luo Hao': 95, 'Bai Yuanfang': 78, 'Di Renjie': 82}  
print(scores)  
# Constructor syntax for creating a dictionary  
items1 = dict(one=1, two=2, three=3, four=4)  
# Create a dictionary by zipping two sequences together  
items2 = dict(zip(['a', 'b', 'c'], '123'))  
# Dictionary comprehension syntax  
items3 = {num: num ** 2 for num in range(1, 10)}  
print(items1, items2, items3)  
# Retrieve values from the dictionary using keys  
print(scores['Luo Hao'])  
print(scores['Di Renjie'])  
# Iterate over all key-value pairs in the dictionary  
for key in scores:  
    print(f'{key}: {scores[key]}')  
# Update elements in the dictionary  
scores['Bai Yuanfang'] = 65  
scores['Zhuge Wanglang'] = 71  
scores.update(ColdFace=67, Fang Qihé=85)  
print(scores)  
if 'Wu Zetian' in scores:  
    print(scores['Wu Zetian'])  
print(scores.get('Wu Zetian'))  
# The get method retrieves the corresponding value using a key but allows specifying a default value  
print(scores.get('Wu Zetian', 60))  
# Remove elements from the dictionary  
print(scores.popitem())  
print(scores.popitem())  
print(scores.pop('Luo Hao', 100))  
# Clear the dictionary  
scores.clear()  
print(scores)  

List

Defining lists, iterating through lists, and performing index operations on lists

list1 = [1, 3, 5, 7, 100]  
print(list1) # [1, 3, 5, 7, 100]  
# The multiplication operator repeats list elements  
list2 = ['hello'] * 3  
print(list2) # ['hello', 'hello', 'hello']  
# Compute the length (number of elements) of the list  
print(len(list1)) # 5  


# Index (subscript) operations  
print(list1[0]) # 1  
print(list1[4]) # 100  
# print(list1[5])  # IndexError: list index out of range  
print(list1[-1]) # 100  
print(list1[-3]) # 5  
list1[2] = 300  
print(list1) # [1, 3, 300, 7, 100]  


# Iterate through list elements using indices in a loop  
for index in range(len(list1)):  
    print(list1[index])  
# Iterate through list elements using a for loop  
for elem in list1:  
    print(elem)  
# Use the enumerate function to iterate through the list and obtain both index and value simultaneously  
for index, elem in enumerate(list1):  
    print(index, elem)  

Slicing

fruits = ['grape', 'apple', 'strawberry', 'waxberry']  
fruits += ['pitaya', 'pear', 'mango']  
# List slicing  
fruits2 = fruits[1:4]  
print(fruits2) # apple strawberry waxberry  
# Perform a full slice to copy the list  
fruits3 = fruits[:]  
print(fruits3) # ['grape', 'apple', 'strawberry', 'waxberry', 'pitaya', 'pear', 'mango']  
fruits4 = fruits[-3:-1]  
print(fruits4) # ['pitaya', 'pear']  
# Perform reverse slicing to obtain a reversed copy of the list  
fruits5 = fruits[::-1]  
print(fruits5) # ['mango', 'pear', 'pitaya', 'waxberry', 'strawberry', 'apple', 'grape']  

Set

Creating sets

# Literal syntax for creating a set  
set1 = {1, 2, 3, 3, 3, 2}  
# Constructor syntax for creating a set (explained in detail in the object-oriented section)  
set2 = set(range(1, 10))  
set3 = set((1, 2, 3, 3, 2, 1))  
# Set comprehension syntax (comprehensions can also be used to generate sets)  
set4 = {num for num in range(1, 100) if num % 3 == 0 or num % 5 == 0}  

Adding and removing elements

set1.add(4)  
set1.add(5)  
set2.update([11, 12])  
set2.discard(5)  
if 4 in set2:  
    set2.remove(4)  
print(set1, set2)  
print(set3.pop())  
print(set3)  

Intersection, union, and difference operations

# Intersection, union, difference, and symmetric difference operations on sets  
print(set1 & set2)  
# print(set1.intersection(set2))  
print(set1 | set2)  
# print(set1.union(set2))  
print(set1 - set2)  
# print(set1.difference(set2))  
print(set1 ^ set2)  
# print(set1.symmetric_difference(set2))  
# Check for subsets and supersets  
print(set2 <= set1)  
# print(set2.issubset(set1))  
print(set3 <= set1)  
# print(set3.issubset(set1))  
print(set1 >= set2)  
# print(set1.issuperset(set2))  
print(set1 >= set3)  
# print(set1.issuperset(set3))  

Conversions among Lists, Tuples, Sets, Dictionaries, and Strings

Transcoded by Jianyue SimpRead; original article at zhuanlan.zhihu.com

  1. Converting between lists and tuples
# Convert a list to a tuple  
li = [1, 2, 3]  
t = tuple(li)  
print(t, type(t))  
# Output: (1, 2, 3) <class 'tuple'>  

# Convert a tuple to a list  
tu = (1, 2, 3)  
li = list(tu)  
print(li, type(li))  
# Output: [1, 2, 3] <class 'list'>  
  1. Converting between lists and strings
# Convert a list to a string  
li = ['H', 'e', 'l', 'l', 'o']  
str1 = ''.join(li)  
print(str1, type(str1))  
# Output: Hello <class 'str'>  

# Convert a string to a list  
str2 = 'hello python'  
li1 = str2.split(' ')  
print(li1, type(li1))  
# Output: ['hello', 'python'] <class 'list'>  
  1. Converting between lists and dictionaries
# Method 1: Convert lists to a dictionary  
list1 = ['name', 'age', 'sex']  
list2 = ['Zhang San', 18, 'male']  
dict = {}  
for i in range(len(list1)):  
    dict[list1[i]] = list2[i]  
print(dict, type(dict))  
# Output: {'name': 'Zhang San', 'age': 18, 'sex': 'male'} <class 'dict'>  

# Method 2: Convert lists to a dictionary using the built-in zip function  
list1 = ['name', 'age', 'sex']  
list2 = ['Zhang San', 18, 'male']  
d = dict(zip(list1, list2))  
print(d)  

# Convert a dictionary to a list  
dict = {'name': 'Zhang San', 'age': 18, 'sex': 'male'}  
keys = list(dict.keys())  
values = list(dict.values())  
print(keys, type(keys))  
print(values, type(values))  
  1. Convert a nested list to a dictionary
list3 = [['key1','value1'],['key2','value2'],['key3','value3']]  
print(dict(list3))  
  1. Converting between lists and sets
# Convert a list to a set  
list1 = [1, 3, 4, 3, 2, 1]  
s1 = set(list1)  
print(s1, type(s1))  
# Output: {1, 2, 3, 4} <class 'set'>  

# Convert a set to a list  
list2 = list(s1.intersection(s1))  
print(list2, type(list2))  
# Output: [1, 2, 3, 4] <class 'list'>  
  1. Converting between tuples and strings
# Converting a tuple to a string follows the same method as converting a list to a string  

# To convert a string to a tuple, first convert it to a list, then convert that list to a tuple  
list = []  
a = 'Hello'  
list.append(a)  
print(list)  
b = tuple(list)  
print(b, type(b))  
# Output: ('Hello',) <class 'tuple'>  
  1. Converting between tuples and dictionaries
# Convert a dictionary to a tuple  
dict = {'name': 'Xiao Ming', 'age': 18}  
tup = tuple(dict)  
print(tup)  # Only keys are converted  

tup2 = tuple(dict.values())  
print(tup2)  

# A tuple cannot be directly converted to a dictionary  
  1. Converting between dictionaries and strings
# Convert a dictionary to a string  
dic1 = {'a': 1, 'b': 2}  
str1 = str(dic1)  
# Output: {'a': 1, 'b': 2} <class 'str'>  

# Convert a string to a dictionary  
dic2 = eval("{'name':'Xiao Ming', 'age':18}")  
print(dic2, type(dic2))  
  1. Converting between strings and sets
# Convert a string to a set  
str1 = 'hello'  
s1 = set(str1)  
print(s1, type(s1))  
# Output: {'e', 'o', 'h', 'l'} <class 'set'>  
  1. Swapping dictionary keys and values
dic1 = {'a': 1, 'b': 2, 'c': 3}  
dic2 = {value: key for key, value in dic1.items()}  
print(dic2)