不幸的是,我有一本很大的字典,里面有许多相同的键,而python不允许相同的键并且只打印最后一次出现的键,现在我发现的解决方案是将相同键的值更改为list或tuple。但是我不是能够找到一种自动的方法。我也想保留列表中值的顺序,因为我试图在下面的示例字典中提及它。 我当前的字典看起来像这样:
dic = {
'a' : 2,
'a' : 1,
'b' : 2,
'a' : 4,
'a' : 3,
'b' : 1,
'b' : 2,
'c': 1
}
现在根据解决方案应将其转换为:
dic = {
'a' : [2,1,4,3],
'b' : [2,1,2],
'c': 1
}
谢谢。
答案 0 :(得分:1)
您需要首先探查字典中是否已经包含您要为其添加新值的键。确定键是否已存在后,可以检查返回的值是单个数字还是数字列表,并采取相应的措施。
使用伪代码:
# Get current value associated with new key in dict.
# If returned value is None, add new value for key in question.
# Else If returned value is a list, append new value to list, store list for key in question
# Else, returned value was a single number; create a list of returned value and new value. Store list for key in question.
Python解决方案:
class DictUtil(object):
""" A utility class that automates handling of key collisions for a dictionary object. """
@staticmethod
def add_to_dict(dict, new_key, new_value):
# Get whatever currently exists within the dictionary for the given key.
value_in_dict = dict.get(new_key)
# If the value for the given key is None, there is no current entry, so we can add the new value.
if value_in_dict is None:
dict[new_key] = new_value
# If the value for a given key returned a list, append new value to list and re-store in dict.
elif type(value_in_dict) in [list, tuple]:
dict[new_key].append(new_value)
# Otherwise, the get returned a single item. Make a list of the returned value and the new value and re-store.
else:
dict[new_key] = [value_in_dict, new_value]
def main():
""" Entry point for an example script to demonstrate Dictutil functionality. """
dict = {}
# Populating values in dict using Dictutil method: add_to_dict:
DictUtil.add_to_dict(dict, 'a', 2)
DictUtil.add_to_dict(dict, 'a', 1)
DictUtil.add_to_dict(dict, 'b', 2)
DictUtil.add_to_dict(dict, 'a', 4)
DictUtil.add_to_dict(dict, 'a', 3)
DictUtil. add_to_dict(dict, 'b', 1)
DictUtil.add_to_dict(dict, 'b', 2)
DictUtil.add_to_dict(dict, 'c', 1)
# Printing dictionary contents
for key, value in dict.iteritems():
print 'Key: %s \t Value: %s' % (key, value)
if __name__ == '__main__':
main()