I have an dictonary for my input with the following characteristics:
- Each value will be either an integer, string or iterable (other than a string).
- If the element is an iterable, each element in that iterable will only be a string or integer.
ex:
mydict = {
'one': 1,
'two': '23',
'three': 3,
'four': [
7,
'6',
5,
8
],
'nine': 9
}
I need to convert the input to a list of tuples where each tuple is a key/value pair. For iterable elements, there will be a key/value pair for each of its elements, sorted by value. For example, output for the above should be:
('four', 5)
('four', 7)
('four', 8)
('four', '6')
('nine', 9)
('one', 1)
('three', 3)
('two', '2')
I currently have this implemented using the following generator:
def dict_to_sorted_tuples(unsorted_dict):
for key in sorted(unsorted_dict):
if isinstance(unsorted_dict[key], basestring):
yield key, unsorted_dict[key]
continue
try:
for v in sorted(unsorted_dict[key]):
yield key, v
except:
yield key, unsorted_dict[key]
print list(dict_to_sorted_tuples(mydict))
I feel this can be done in a cleaner fashion, any suggestions for improvements?
The idea here is that if the value is an
intor astr, you put it in alist. Now the problem is simplified because you have a value you can always iterate overIf you are really sure you only need to check for
intorstr(not subclasses or unicode), you could just useIf the value can be unicode, you should use
isinstance(j, basestring)instead ofisinstance(j, str)