如何为字典值生成随机密钥?

问题描述 投票:0回答:1

我必须使用哈希码随机生成字典键。我无法弄清楚这个问题的方法。我提到的字典键是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']}}
python dictionary hashcode
1个回答
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']}}

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

© www.soinside.com 2019 - 2024. All rights reserved.