Home > other >  Questions about the dictionary to unpack the assignment
Questions about the dictionary to unpack the assignment

Time:11-21

X={' a ':' 1 '}
The key, value=https://bbs.csdn.net/topics/x.items ()
The result error: ValueError: not enough values to unpack (expected 2, 1) got

X={' a ':' 1 '}
For the key and the value in x.i tems () :
Print (key, value)
The results were not an error: a 1

Why as a view object iteration of the dictionary, can respectively in the loop to assign keys and values to the key and the value of variables, but it can not directly be unpacked and assigns values to the key and the value of variables?

CodePudding user response:

ddddddd

CodePudding user response:

Understand:
Sequence unpacking can be used to tuples, lists, dictionaries, sequence unpacking can make us convenient to multiple variable assignment,

X, y, z=(10, 30)
Print (x) # results: 10
Print (y) # results: 20
Print (z) # results: 30

(a, b, c)=(40,50,60)
# print (a) result: 40
# print (b) results: 50
Print (c) # results: 60

[q, w, e]=[70,80,90]
Print (q) # : 70
Print (w) # : 80
Print (e) # : 90

Sequence unpacking for a dictionary, is the default to "key" to operate;
If you need to the key value to operation, you need to use the items ();
If you need to "value", you will need to use values ();

S={' name ':' gaoqi ', 'age: 18,' job ':' the teacher '}
A, b, c=s # default is key as variable values assigned to more than one variable
# print (a) results: job
# print (b) the results: the age
Print (c) # results: name

A, b, c=s.v alues (#) will be "value" as the value assigned to multiple variables
# print (a) results: gaoqi
# print (b) results: 18
Print (c #) result: the teacher

A, b, c=s.i tems (#) will be "key/value" as the value assigned to multiple variables
# print (a) the results: (' name ', 'gaoqi')
# print (b) the results: (' age, 18)
Print (c) result # : (' job ', 'the teacher')
Print (a [0]) # results: name, again through the tuples index access method for each value
Print (a [1]) # results: gaoqi
The above content comes from: https://blog.csdn.net/u014612521/article/details/100520899? Utm_medium=distribute. Pc_relevant_bbs_down. None - task - 2 ~ all ~ first_rank_v2 ~ rank_v28-5. Nonecase& Depth_1 - utm_source=distribute. Pc_relevant_bbs_down. None - task - 2 ~ all ~ first_rank_v2 ~ rank_v28-5. Nonecase

CodePudding user response:

The study,
X={' a ':' 1 '}
The key, value=https://bbs.csdn.net/topics/x.keys (), x.v alues ()

CodePudding user response:

X.i tems () returns a view object, not assigned to two different variable!
So to write:
X
{' a ': 1}
> The key, value=https://bbs.csdn.net/topics/tuple (x.i tems ()) [0]
> The key, the value
(' a ', 1)
  • Related