How to Convert a Dictionary into a List of Tuples

How can I convert a dictionary into a list of tuples?

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]

For Python 3.6 and later, the order of the list is what you would expect.

In Python 2, you don't need list.

Convert a nested dictionary into list of tuples

If you're not sure how many levels this list may have, it seems that what you need is recursion:

def unnest(d, keys=[]):
result = []
for k, v in d.items():
if isinstance(v, dict):
result.extend(unnest(v, keys + [k]))
else:
result.append(tuple(keys + [k, v]))
return result

Just a friendly reminder: before Python 3.6, dict order is not maintained.

[('complaints', '2014', 'sfdwa.csv', 'c2c2jh'),
('revenues', '201906', 'ddd.csv', 'e4c5q'),
('revenues', '201907', 'aaa.csv', 'fdwe34x2')]

Converting Dictionary to Sorted List of Tuples

I think what you are looking for is something like:

def sort_contacts(diction):
sorta = [(k, v[0], v[1]) for k,v in diction.items()]
# sort it somehow?
return sorta

Convert Dictionary to a list of Tuples

Something like this?

var list = myDico.Select(x => new Tuple<long, int>(x.Key, x.Value)).ToList();

Converting a dictionary into a list of Values/Tuples

try this:

dict1 = {'a':9, 'b':17, 'c':17, 'd':3}
print([item[::-1] for item in sorted(dict1.items())])

Output:

[(9, 'a'), (17, 'b'), (17, 'c'), (3, 'd')]

Cannot convert a dictionary into list of tuples and sort it

You should declare sorted_dict_list outside the first for loop, otherwise each time you go through the loop you have a new empty list. On top of that, your loop through sorted_dict_list is inside the first for loop.

So each time you loop through the outer loop you create an empty list, add the next key-value pair into it, run through the list (which is only one item long) and print out the values. Basically you are just printing out each key-value pair as you go through.

You need to move the list declaration outside the loop and un-indent the second loop.

sorted_dict_list = []
for key, value in data_dict.iteritems():
sorted_dict_list.append((key, value["salary"], value["bonus"]))
sorted_dict_list.sort(key=lambda tup: tup[1])

for tuple in sorted_dict_list:
print tuple

This might be a better solution:

def sortKey(item):
return item[1]

sorted_dict = [(key, value['salary'], value['bonus']) for key, value in data_dict.items()]
sorted_dict = sorted(sorted_dict, key=sortKey)

for item in sorted_dict:
print(item)

Python how to convert a list of dict to a list of tuples

You can use list comprehension for that:

new_list = [(key,)+tuple(val) for dic in list for key,val in dic.items()]

Here we iterate over all dictonaries in list. For every dictionary we iterate over its .items() and extract the key and value and then we construct a tuple for that with (key,)+val.

Whether the values are strings or not is irrelevant: the list comprehension simply copies the reference so if the original elements were Foos, they remain Foos.

Finally note that the dictionaries are unordered, so the order is undetermined. However if a dictionary d1 occurs before a dictionary d2, all the elements of the first will be placed in the list before the tuples of the latter. But the order of tuples for each individual dictionary is not determined.

Convert values-as-list of a dictionary to values-as-tuple (python)

You can use a dict comprehension:

out = {k:tuple(v) for k,v in d.items()}

or map with lambda:

out = dict(map(lambda x: (x[0],tuple(x[1])), d.items()))

or map with zip:

out = dict(zip(d.keys(), map(tuple, d.values())))

Output:

{'a': ('b', 'c'), 'b':('a', 'c', 'e'), 'c':('a', 'b', 'f')}


Related Topics



Leave a reply



Submit