开发者

Python dictionary to sorted tuples, can this be done better?

开发者 https://www.devze.com 2023-03-14 18:41 出处:网络
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).

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开发者_如何学Go(dict_to_sorted_tuples(mydict))

I feel this can be done in a cleaner fashion, any suggestions for improvements?


>>> sorted((i,k) for i,j in mydict.items() for k in ([j] if isinstance(j, str) or isinstance(j, int) else j))
[('four', 5), ('four', 7), ('four', 8), ('four', '6'), ('nine', 9), ('one', 1), ('three', 3), ('two', '2')]

The idea here is that if the value is an int or a str, you put it in a list. Now the problem is simplified because you have a value you can always iterate over

If you are really sure you only need to check for int or str (not subclasses or unicode), you could just use

sorted((i,k) for i,j in mydict.items() for k in ([j] if type(j) in (int, str) else j))

If the value can be unicode, you should use isinstance(j, basestring) instead of isinstance(j, str)


for values in sorted(mydict.items()):
    if isinstance(values[1], list):
        for x in sorted(values[1]):
            print (values[0], x,)
    else:
        print values


def dict_to_sorted_tuples(unsorted_dict):
    res = []
    for k, v in sorted(unsorted_dict.iteritems()):
        if isinstance(v, (list, tuple)):
            res.extend((k, _v) for _v in sorted(v))
        else:
            res.append((k, v))
    return res
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号