13 ways of connection combination and mutual conversion of basic types in python

Keywords: Python

This article summarizes the following small examples of string, list, dictionary, tuple connection combination and type conversion, especially the extend() method in the list and the

The update method is very common.

1. Connect two strings

a = "hello "
b = "world"
a += b
print(a)  # hello world

2. Dictionary connection

dict1 = {1: "a", 2: "b"}
dict2 = {3: "c", 4: "d"}
dict1.update(dict2)
print(dict1)  # {1: 'a', 2: 'b', 3: 'c', 4: 'd'}

3. List connection

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)  # [1, 2, 3, 4, 5, 6]
print(list1)

4. Connection of tuples

tuple1 = (1, 2)
tuple2 = (3, 4)
tuple1 += tuple2
print(tuple1)  # (1, 2, 3, 4)

5. Convert dictionary to string

dict1 = {1: "a", 2: "b"}
str1 = str(dict1)
print(str1)  # {1: 'a', 2: 'b'}
print(type(str1))  # <class 'str'>

PS: no one answers the questions? Need Python learning materials? You can click the link below to get it by yourself
note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee34324d76

6. Dictionary to list

dict1 = {1: "a", 2: "b"}
list1 = list(dict1.keys())
list2 = list(dict1.values())
list3 = list(dict1)
print(list1)  # [1, 2]
print(list2)  # ['a', 'b']
print(list3)  # [1,2]

7. Dictionary to tuple

dict1 = {1: "a", 2: "b"}
tuple1 = tuple(dict1.keys())
tuple2 = tuple(dict1.values())
tuple3 = tuple(dict1)
print(tuple1)  # (1, 2)
print(tuple2)  # ('a', 'b')
print(tuple3)  # (1, 2)

8. Convert list to string

list1 = [1, 2, 3]
str1 = str(list1)
print(str1)  # [1, 2, 3]
print(type(str1))  # <class 'str'>

9. List to dictionary

# 1.
list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
dict1 = dict(zip(list1, list2))
print(dict1)  # {1: 'a', 2: 'b', 3: 'c'}
# 2.
dict1 = {}
for i in list1:
    dict1[i] = list2[list1.index(i)]
print(dict1)  # {1: 'a', 2: 'b', 3: 'c'}
# 3.
list1 = [[1, 'a'], [2, 'b'], [3, 'c']]
dict1 = dict(list1)
print(dict1)  # {1: 'a', 2: 'b', 3: 'c'}

10. Convert list to tuple

list1 = [1, 2, 3]
tuple1 = tuple(list1)
print(tuple1)  # (1, 2, 3)

11. Tuple to string

tuple1 = (1, 2, 3)
str1 = tuple(tuple1)
print(str1)  # (1, 2, 3)
print(type(str1))  # <class 'tuple'>

12. Tuple to dictionary

# 1.
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
dict1 = dict(zip(tuple1, tuple2))
print(dict1)  # {1: 4, 2: 5, 3: 6}
# 2
dict1 = {}
for i in tuple1:
    dict1[i] = tuple2[tuple1.index(i)]
print(dict1)  # {1: 4, 2: 5, 3: 6}

# 3
tuple1 = (1, 2)
tuple2 = (4, 5)
tuple3 = (tuple1, tuple2)
dict1 = dict(tuple3)
print(dict1)  # {1: 2, 4: 5}

13. Tuple to list

tuple1 = (1, 2)
list1 = list(tuple1)
print(list1)  # [1, 2]

Posted by jeboy on Sat, 14 Dec 2019 06:01:58 -0800