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

时间:2019-04-10 10:00:58

标签: python dictionary hashcode

我必须使用哈希码为字典随机生成密钥。我无法找出解决此问题的方法。我提到的字典键是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']}}

1 个答案:

答案 0 :(得分: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']}}

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

相关问题