简体   繁体   中英

How to convert this dictionary into a list of tuples?

I have this dictionary;

Dict={1: ('John', 129L, 37L), 2: ('James', 231L, 23L)}

I want to convert it into a list of tuples that look like this;

List=[(1, 'John', 129L, 37L), (2, 'James', 231L, 23L)]

I tried Dict.items() but it did not yield the desirable results but was close. What is the correct solution?

I am using Python 2.7

Using list comprehension :

>>> d = {1: ('John', 129L, 37L), 2: ('James', 231L, 23L)}
>>> [(key,) + value for key, value in d.iteritems()]
[(1, 'John', 129L, 37L), (2, 'James', 231L, 23L)]

BTW, the order of items in the generated list is not guaranteed. Because dict is a unordered mapping.

If you want the result to be ordered by keys, use sorted :

>>> [(key,) + value for key, value in sorted(d.iteritems())]
[(1, 'John', 129L, 37L), (2, 'James', 231L, 23L)]
my_dict = {1: ('John', 129L, 37L), 2: ('James', 231L, 23L)} 
print [(k,) + my_dict[k] for k in my_dict]
# [(1, 'John', 129L, 37L), (2, 'James', 231L, 23L)]

Sorted by keys version:

print [(k,) + my_dict[k] for k in sorted(my_dict)]

Explanation:

(k,) + my_dict[k] is extending the tuple (k,) (Yes, a single item, with comma, inside parens is a tuple) by concatenating with the values corresponding to the key k

Using map:

map(lambda x: (x,) + Dict[x] , Dict.keys())

Output:

[(1, 'John', 129L, 37L), (2, 'James', 231L, 23L)]

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