简体   繁体   中英

How to generate random keys for dictionary values?

I have to randomly generate keys for dictionary using hashcode. I am unable to figure out the way to this problem. The dictionary key I have mentioned is 1,2,3,4 which needs to be auto generated.

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']}}

Random key generation, as mentioned will not be useful because can result in duplicate keys.

However, one of the interim solution to your problem with auto incremented keys is:

>>> 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']}}

You can also put in your methods of adding the dictionary values instead of user input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM