【问题标题】:How to generate random keys for dictionary values?如何为字典值生成随机键?
【发布时间】:2019-04-10 10:00:58
【问题描述】:

我必须使用哈希码随机生成字典的键。我无法找出解决这个问题的方法。我提到的字典键是1,2,3,4,需要自动生成。

d = {1:{'fname':['B'],
'parent' : ['A'],
 'child': ['C','D']},
2:{ 'fname' : ['C'],
'parent' : ['B'],
'child' : ['C1','C2']},
   3: { 'fname' : ['D'],
 'parent' : ['B'],
  'child': ['D1','D2']},
    4:{ 'fname' : ['C1'],
            'parent' : ['C'],
            'child': ['X']}}

【问题讨论】:

  • 如果随机生成密钥,你将如何确保它们的唯一性?
  • 请使用显示解决此问题的尝试的代码更新您的问题。您可以编写包含以下行的内容:d[make_hash_code()] = obj,然后您可以询问应该如何编写 def make_hash_code():

标签: python dictionary hashcode


【解决方案1】:

如前所述,随机密钥生成不会有用,因为可能会导致重复密钥。

但是,解决auto incremented keys 问题的临时解决方案之一是:

>>> dic = dict()
>>> dic
{}
>>> n=int(input("Enter the total number of dictionary items to be entered: "))
Enter the total number of dictionary items to be entered: 3

>>> for k in range(n):
...     dic[k]=input("Enter the value for "+str(k)+": ")
...
Enter the value for 0: {'fname':['B'],'parent' : ['A'],'child': ['C','D']}
Enter the value for 1: {'fname':['C'],'parent' : ['B'],'child': ['C1','C2']}
Enter the value for 2: {'fname':['D'],'parent' : ['B'],'child': ['D1','2']}
>>> dic
{0: {'parent': ['A'], 'fname': ['B'], 'child': ['C', 'D']}, 
1: {'parent': ['B'], 'fname': ['C'], 'child': ['C1', 'C2']}, 
2: {'parent': ['B'], 'fname': ['D'], 'child': ['D1', '2']}}

您还可以输入添加字典值的方法,而不是用户输入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-02
    • 2017-02-27
    • 1970-01-01
    • 2010-11-06
    • 2023-02-04
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    相关资源
    最近更新 更多