Python realizes the mutual conversion among list tuple str and dict
- 2021-09-20 21:12:00
- OfStack
1. Dictionary (dict)
dict = { ' name': ' Zara', ' age': 7, ' class': ' First'}
1.1 Dictionary-String
Return to:
print type(str(dict)), str(dict)
1.2 Dictionary-Tuples
Returns: ('age', 'name', 'class')
print tuple(dict)
1.3 Dictionary-Tuples
Return: (7, 'Zara', 'First')
print tuple(dict.values())
1.4 Dictionary-List
Return: ['age', 'name', 'class']
print list(dict)
1.5 Dictionary-List
print dict.values
2. Tuples
tup=(1, 2, 3, 4, 5)
2.1 Tuple-String
Return: (1, 2, 3, 4, 5)
print tup.__str__()
2.2 tuple-list
Return: [1, 2, 3, 4, 5]
print list(tup)
2.3 Tuples cannot be converted to dictionaries
3. List
nums=[1, 3, 5, 7, 8, 13, 20];
3.1 List-String
Return: [1, 3, 5, 7, 8, 13, 20]
print type(str(dict)), str(dict)
0
3.2 List-Tuples
Return: (1, 3, 5, 7, 8, 13, 20)
print type(str(dict)), str(dict)
1
3.3 Lists cannot be converted to dictionaries
4. String
4.1 String--Tuples
Return: (1, 2, 3)
print type(str(dict)), str(dict)
2
4.2 String--List
Return: [1, 2, 3]
print list(eval("(1,2,3)"))
4.3 String--Dictionary
Return to:
print type(str(dict)), str(dict)
4
Supplement: python Getting Started: 1 Small Mistake, str Changed to tuple
When I was programming, I found that the original definition of str string will inexplicably change its type and become tuple when passing and referencing.
print type(str(dict)), str(dict)
5
Here the random_char function outputs a random string, and you can see that the type type is:
print type(str(dict)), str(dict)
6
Reference in another file:
print type(str(dict)), str(dict)
7
It is found that the type type of random_char has changed:
<class 'tuple'>
It's just a simple assignment. Why did it change?
The reason is that an extra comma is added when assigning values.
This comma is understood by the compiler when it executes ("str",)