编辑:我的问题已经得到了很多后续问题,因为从表面上看,它似乎没有任何意义。对于大多数人来说,词典是解决这个问题的不合逻辑的方法。我同意,并且对我的约束感到沮丧(在评论中解释)。在我的场景中,原始KV对将被编码为要由另一个服务器使用ObjectID读取的数据。但是,必须将其作为字典输入编码功能。顺序无关紧要,但必须为KV对赋予新的唯一值。原始KV对将最终作为新字典中的新字符串键,ObjectID作为新的唯一值。
请记住,我使用的是Python 2.7。
请注意,这是在我给出的约束内呈现由ObjectID值编码的字典(dictA)的问题。
我有一本字典,比如dictA = {'a':'10', 'b':'20', 'c':'30'}
,我有一个ObjectIdentifier('n')
列表,其中n
是一个数字。创建dictB
的最佳方法是什么,以便dictB
是一个新词典,其密钥等于dictA
的键:值对,值等于列表中对应的ObjectIdentifier('n')
。
新的dictB
应该是:
{"'a':'10'":ObjectIdentifier('n'), "'b':'20'":ObjectIdentifier('n+1'), "'c':'30'":ObjectIdentifier('n+2')}
如果那有意义的话。
问题是没有订购字典。所以你说
dictA = {'a':'10', 'b':'20', 'c':'30'}
但就python知道它可能是
dictA = {'c':'30', 'a':'10', 'b':'20'}
因为词典没有订单。
你可以像这样创建你的dict:
result = {key: ObjectIdentifier(n+pos) for pos, key in enumerate(dictA.items())}
但是,没有办法确定哪个键会落在哪个位置,因为正如我所说,词典没有顺序。
如果你想要字母顺序,只需使用sorted()
result = {key: ObjectIdentifier(n+pos)
for pos, key in enumerate(sorted(dictA.items()))}
我不知道你为什么会这样
def ObjectIdentifier(n):
print(n)
return "ObjectIdentifier("+ str(n) + ")"
dictA = {'a':'10', 'b':'20', 'c':'30'}
dictB = {}
for n, key in enumerate(sorted(dictA.keys())):
dictB[key] = {dictA[key] : ObjectIdentifier(str(n))}
输出:
{'a': {'10': 'ObjectIdentifier(0)'}, 'b': {'20': 'ObjectIdentifier(1)'}, 'c': {'30': 'ObjectIdentifier(2)'}}