简体   繁体   中英

Extract particular position from all tuples in dictionary keys

From a dictionary whose keys are (x, y) pairs, I would like to get the list of all x's and the list of all y's.

This is how my dictionary looks:

(x, y) : value

{(17, 19): 1, (22, 24): 0, (18, 24): 1}

The goal is:

x={17,22,18} and y={19,24,24}
d ={(17, 19): 1, (22, 24): 0, (18, 24): 1}
x,y = zip(*d)
x,y

Output:

((17, 22, 18), (19, 24, 24))

Solution Without using zip:

x = [ i[0] for i in d ]
y = [ i[1] for i in d ]

Its a dictionary and to get keys in separate lists, you can use list comprehension

d ={(17, 19): 1, (22, 24): 0, (18, 24): 1}

x = [i[0] for i in d.keys()]
y = [i[1] for i in d.keys()]

x
[17, 22, 18]

y
[19, 24, 24]

Here is an interactive demonstration of one approach using destructuring assignment:

>>> d = {(17, 19): 1, (22, 24): 0, (18, 24): 1}
>>> k = d.keys()
>>> x = [k1 for (k1,k2) in k]
>>> x
[18, 17, 22]
>>> y = [k2 for (k1,k2) in k]
>>> y
[24, 19, 24]
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM