将字典拆分成两半? [英] Split a dictionary in half?
本文介绍了将字典拆分成两半?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将字典分成两半的最佳方法是什么?
What is the best way to split a dictionary in half?
d = {'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4, 'key5': 5}
我正在这样做:
d1 = {'key1': 1, 'key2': 2, 'key3': 3}
d2 = {'key4': 4, 'key5': 5}
每个键中的键/值都无关紧要.我只是在寻找将字典一分为二的最简单方法.
It does not matter which keys/values go into each dictionary. I am simply looking for the simplest way to divide a dictionary into two.
推荐答案
这可以工作,尽管我没有测试边缘情况:
This would work, although I didn't test edge-cases:
>>> d = {'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4, 'key5': 5}
>>> d1 = dict(d.items()[len(d)/2:])
>>> d2 = dict(d.items()[:len(d)/2])
>>> print d1
{'key1': 1, 'key5': 5, 'key4': 4}
>>> print d2
{'key3': 3, 'key2': 2}
在python3中:
d = {'key1': 1, 'key2': 2, 'key3': 3, 'key4': 4, 'key5': 5}
d1 = dict(list(d.items())[len(d)//2:])
d2 = dict(list(d.items())[:len(d)//2])
还请注意,不能保证商品的顺序
Also note that order of items is not guaranteed
这篇关于将字典拆分成两半?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文