Python字典到排序元组,这可以做得更好吗?
我的输入有一个具有以下特征的字典:
- 每个值都是整数、字符串或可迭代的(字符串除外)。
- 如果元素是可迭代的,则该可迭代中的每个元素将只是字符串或整数。
例如:
mydict = {
'one': 1,
'two': '23',
'three': 3,
'four': [
7,
'6',
5,
8
],
'nine': 9
}
我需要将输入转换为元组列表,其中每个元组都是一个键/值对。对于可迭代元素,每个元素都有一个键/值对,按值排序。例如,上述输出应该是:
('four', 5)
('four', 7)
('four', 8)
('four', '6')
('nine', 9)
('one', 1)
('three', 3)
('two', '2')
我目前使用以下生成器实现了此功能:
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里的想法是,如果值是
int
或str
,则将其放入list
中。现在问题被简化了,因为你有一个可以随时迭代的值如果你确实确定只需要检查
int
或str
(不是子类或 unicode),你可以只使用如果值可以是unicode,你应该使用
isinstance(j, basestring)
而不是isinstance(j, str)
The idea here is that if the value is an
int
or 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
int
orstr
(not subclasses or unicode), you could just useIf the value can be unicode, you should use
isinstance(j, basestring)
instead ofisinstance(j, str)