创建一个包含每个键的元素数的新字典

时间:2013-10-13 16:55:38

标签: python dictionary

所以我有一个看起来像这样的字典,我想创建一个具有相同键的不同字典,但值是与每个键关联的元素数量。 (例如29:['5'],30:['6'],31:['1'])

 29: ['15', '26', '16', '24', '4'],
 30: ['25', '16', '18', '21', '19', '4'],
 31: ['2'],
 32: ['17', '20', '4'],
 33: ['28', '20', '22', '4'],
 34: ['24', '30', '9', '4', '36'],
 35: ['33', '27', '22', '23', '32', '40', '17', '10', '20', '27', '28', '5'],
 36: ['34', '5', '39'],
 37: ['30', '28', '25', '29', '24', '21', '5'],
 38: ['29', '27', '33', '35', '22', '26', '4'],
 39: ['2'],
 40: ['4', '41'],
 41: ['40', '23', '20', '3'],
 42: ['36', '21', '31', '2'],
 43: ['35', '28', '37', '5'],
 44: ['38', '20', '33', '28', '4', '48', '45'],
 45: ['38', '43', '29', '30', '4'],
 46: ['39', '34', '42', '31', '36', '2'],
 47: ['41', '32', '20', '32', '40', '2'],
 48: ['45', '44', '38', '37', '49', '37', '43', '4'],
 49: ['48', '35', '43', '44', '43', '45', '3']}

1 个答案:

答案 0 :(得分:2)

使用字典理解迭代旧字典并使用以下代码创建新字典:

>>> old_dict = {29: ['15', '26', '16', '24', '4'], 30: ['25', '16', '18', '21', '19', '4'], 31: ['2'], 32: ['17', '20', '4'], 33: ['28', '20', '22', '4'], 34: ['24', '30', '9', '4', '36'], 35: ['33', '27', '22', '23', '32', '40', '17', '10', '20', '27', '28', '5'], 36: ['34', '5', '39'], 37: ['30', '28', '25', '29', '24', '21', '5'], 38: ['29', '27', '33', '35', '22', '26', '4'], 39: ['2'], 40: ['4', '41'], 41: ['40', '23', '20', '3'], 42: ['36', '21', '31', '2'], 43: ['35', '28', '37', '5'], 44: ['38', '20', '33', '28', '4', '48', '45'], 45: ['38', '43', '29', '30', '4'], 46: ['39', '34', '42', '31', '36', '2'], 47: ['41', '32', '20', '32', '40', '2'], 48: ['45', '44', '38', '37', '49', '37', '43', '4'], 49: ['48', '35', '43', '44', '43', '45', '3']}
>>> new_dict = {k:len(v) for k,v in old_dict.iteritems()}
>>> print new_dict
 {32: 3, 33: 4, 34: 5, 35: 12, 36: 3, 37: 7, 38: 7, 39: 1, 40: 2, 41: 4, 42: 4, 43: 4, 44: 7, 45: 5, 46: 6, 47: 6, 48: 8, 49: 7, 29: 5, 30: 6, 31: 1}