Technical otaku
2022-01-18
# -*- coding: UTF-8 -*-
"""
@author:AmoXiang
@file:2. How to convert lists, tuples, sets and dictionaries to each other.py
@time:2020/11/10
"""
# 1. Convert list tuples to other types
# List to set (de-duplication)
list1 = [ 6 , 7 , 7 , 8 , 8 , 9 ]
print ( set ( list1 )) # {8, 9, 6, 7}
# Two lists to dictionary
list1 = [ 'key1' , 'key2' , 'key3' ]
list2 = [ '1' , '2' , '3' ]
print ( dict ( zip ( list1 , list2 ))) # {'key1': '1', 'key2': '2', 'key3': '3'}
# Nested list to dictionary
list3 = [[ 'key1' , 'value1' ], [ 'key2' , 'value2' ], [ 'key3' , 'value3' ]]
# {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
print ( dict ( list3 ))
# list, tuple to string
list2 = [ 'a' , 'a' , 'b' ]
print ( "" . join ( list2 )) # aab
tuple1 = ( 'a' , 'a' , 'b' )
print ( "" . join ( tuple1 )) # aab
print ( "----------------------------------------------- -------------" )
# 2. Dictionaries are converted to other types
# Dictionaries are converted to other types
dic1 = { 'a' : 1 , 'b' : 2 }
print ( str ( dic1 )) # "{'a': 1, 'b': 2}"
print ( type ( str ( dic1 ))) # <class 'str'>
# dictionary key and value conversion
dic2 = { 'a' : 1 , 'b' : 2 , 'c' : 3 }
# {1: 'a', 2: 'b', 3: 'c'}
print ({ value : key for key , value in dic2 . items ()})
print ( "----------------------------------------------- -------------" )
# 3. Convert string to other type
# string to list
s = "aabbcc"
print ( list ( s )) # ['a', 'a', 'b', 'b', 'c', 'c']
# string to tuple
print ( tuple ( s )) # ('a', 'a', 'b', 'b', 'c', 'c')
# String to collection
print ( set ( s )) # {'a', 'b', 'c'}
# string to dictionary
dic2 = eval ( "{'name': 'Amo', 'age': 18}" )
print ( dic2 ) # {'name': 'Amo', 'age': 18}
print ( type ( dic2 )) # <class 'dict'>
# split the string
a = "ab c"
print ( a . split ( ' ' )) # ['a', 'b', 'c']
0 Comments