utils_dict.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import random
  2. from collections import OrderedDict
  3. def get_dict_first_item(dict_obj):
  4. for key in dict_obj:
  5. return key, dict_obj[key]
  6. def sort_dict(dict_obj, key=None, reverse=False):
  7. return OrderedDict(sorted(dict_obj.items(), key=key, reverse=reverse))
  8. def create_multidict(key_list, value_list):
  9. assert len(key_list) == len(value_list)
  10. multidict_obj = {}
  11. for key, value in zip(key_list, value_list):
  12. multidict_obj.setdefault(key, []).append(value)
  13. return multidict_obj
  14. def convert_multidict_to_list(multidict_obj):
  15. key_list, value_list = [], []
  16. for key, value in multidict_obj.items():
  17. key_list += [key] * len(value)
  18. value_list += value
  19. return key_list, value_list
  20. def convert_multidict_to_records(multidict_obj, key_map=None, raise_if_key_error=True):
  21. records = []
  22. if key_map is None:
  23. for key in multidict_obj:
  24. for value in multidict_obj[key]:
  25. records.append('{},{}'.format(value, key))
  26. else:
  27. for key in multidict_obj:
  28. if raise_if_key_error:
  29. mapped_key = key_map[key]
  30. else:
  31. mapped_key = key_map.get(key, key)
  32. for value in multidict_obj[key]:
  33. records.append('{},{}'.format(value, mapped_key))
  34. return records
  35. def sample_multidict(multidict_obj, num_keys, num_per_key=None):
  36. num_keys = min(num_keys, len(multidict_obj))
  37. sub_keys = random.sample(list(multidict_obj), num_keys)
  38. if num_per_key is None:
  39. sub_mdict = {key: multidict_obj[key] for key in sub_keys}
  40. else:
  41. sub_mdict = {}
  42. for key in sub_keys:
  43. num_examples_inner = min(num_per_key, len(multidict_obj[key]))
  44. sub_mdict[key] = random.sample(multidict_obj[key], num_examples_inner)
  45. return sub_mdict
  46. def split_multidict_on_key(multidict_obj, split_ratio, use_shuffle=False):
  47. """Split multidict_obj on its key.
  48. """
  49. assert isinstance(multidict_obj, dict)
  50. assert isinstance(split_ratio, (list, tuple))
  51. pdf = [k / float(sum(split_ratio)) for k in split_ratio]
  52. cdf = [sum(pdf[:k]) for k in range(len(pdf) + 1)]
  53. indices = [int(round(len(multidict_obj) * k)) for k in cdf]
  54. dict_keys = list(multidict_obj)
  55. if use_shuffle:
  56. random.shuffle(dict_keys)
  57. be_split_list = []
  58. for i in range(len(split_ratio)):
  59. #if indices[i] != indices[i + 1]:
  60. part_keys = dict_keys[indices[i]: indices[i + 1]]
  61. part_dict = dict([(key, multidict_obj[key]) for key in part_keys])
  62. be_split_list.append(part_dict)
  63. return be_split_list
  64. def split_multidict_on_value(multidict_obj, split_ratio, use_shuffle=False):
  65. """Split multidict_obj on its value.
  66. """
  67. assert isinstance(multidict_obj, dict)
  68. assert isinstance(split_ratio, (list, tuple))
  69. pdf = [k / float(sum(split_ratio)) for k in split_ratio]
  70. cdf = [sum(pdf[:k]) for k in range(len(pdf) + 1)]
  71. be_split_list = [dict() for k in range(len(split_ratio))]
  72. for key, value in multidict_obj.items():
  73. indices = [int(round(len(value) * k)) for k in cdf]
  74. cloned = value[:]
  75. if use_shuffle:
  76. random.shuffle(cloned)
  77. for i in range(len(split_ratio)):
  78. #if indices[i] != indices[i + 1]:
  79. be_split_list[i][key] = cloned[indices[i]: indices[i + 1]]
  80. return be_split_list
  81. def get_multidict_info(multidict_obj, with_print=False, desc=None):
  82. num_list = [len(val) for val in multidict_obj.values()]
  83. num_keys = len(num_list)
  84. num_values = sum(num_list)
  85. max_values_per_key = max(num_list)
  86. min_values_per_key = min(num_list)
  87. if num_keys == 0:
  88. avg_values_per_key = 0
  89. else:
  90. avg_values_per_key = num_values / num_keys
  91. info = {
  92. 'num_keys': num_keys,
  93. 'num_values': num_values,
  94. 'max_values_per_key': max_values_per_key,
  95. 'min_values_per_key': min_values_per_key,
  96. 'avg_values_per_key': avg_values_per_key,
  97. }
  98. if with_print:
  99. desc = desc or '<unknown>'
  100. print('{} key number: {}'.format(desc, info['num_keys']))
  101. print('{} value number: {}'.format(desc, info['num_values']))
  102. print('{} max number per-key: {}'.format(desc, info['max_values_per_key']))
  103. print('{} min number per-key: {}'.format(desc, info['min_values_per_key']))
  104. print('{} avg number per-key: {:.2f}'.format(desc, info['avg_values_per_key']))
  105. return info
  106. def filter_multidict_by_number(multidict_obj, lower, upper=None):
  107. if upper is None:
  108. return {key: value for key, value in multidict_obj.items()
  109. if lower <= len(value) }
  110. else:
  111. assert lower <= upper, 'lower must not be greater than upper'
  112. return {key: value for key, value in multidict_obj.items()
  113. if lower <= len(value) <= upper }
  114. def sort_multidict_by_number(multidict_obj, num_keys_to_keep=None, reverse=True):
  115. """
  116. Args:
  117. reverse: sort in ascending order when is True.
  118. """
  119. if num_keys_to_keep is None:
  120. num_keys_to_keep = len(multidict_obj)
  121. else:
  122. num_keys_to_keep = min(num_keys_to_keep, len(multidict_obj))
  123. sorted_items = sorted(multidict_obj.items(), key=lambda x: len(x[1]), reverse=reverse)
  124. filtered_dict = OrderedDict()
  125. for i in range(num_keys_to_keep):
  126. filtered_dict[sorted_items[i][0]] = sorted_items[i][1]
  127. return filtered_dict
  128. def merge_multidict(*mdicts):
  129. merged_multidict = {}
  130. for item in mdicts:
  131. for key, value in item.items():
  132. merged_multidict.setdefault(key, []).extend(value)
  133. return merged_multidict