Python 字典:使 key:value 成为键并附加新值
Python Dictionaries: making the key:value the key and appending new values
编辑:我的问题得到了很多跟进问题,因为从表面上看,它似乎没有任何意义。对于大多数人来说,字典是解决这个问题的不合逻辑的方法。我同意,并且对我的限制感到沮丧(在评论中解释)。在我的场景中,原始 KV 对将被编码为数据,供另一台服务器使用 ObjectID 读取。然而,这必须作为字典输入到编码函数中。顺序无关紧要,但必须为 KV 对赋予新的唯一值。原始 KV 对将作为新字典中的新字符串键结束,ObjectID 作为新的唯一值。
请记住,我使用的是 Python 2.7.
问题
请注意,这是在我给出的限制范围内呈现由 ObjectID 值编码的字典 (dictA) 的问题
我有一本字典,比如 dictA = {'a':'10', 'b':'20', 'c':'30'}
,我有一个 ObjectIdentifier('n')
的列表,其中 n
是一个数字。创建 dictB
的最佳方法是什么,以便 dictB
是一个 key 等于 dictA
的 的新字典key:value 对和 value 等于列表中相应的 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'}
因为字典没有顺序。
你可以这样创建你的字典:
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)'}}
编辑:我的问题得到了很多跟进问题,因为从表面上看,它似乎没有任何意义。对于大多数人来说,字典是解决这个问题的不合逻辑的方法。我同意,并且对我的限制感到沮丧(在评论中解释)。在我的场景中,原始 KV 对将被编码为数据,供另一台服务器使用 ObjectID 读取。然而,这必须作为字典输入到编码函数中。顺序无关紧要,但必须为 KV 对赋予新的唯一值。原始 KV 对将作为新字典中的新字符串键结束,ObjectID 作为新的唯一值。
请记住,我使用的是 Python 2.7.
问题
请注意,这是在我给出的限制范围内呈现由 ObjectID 值编码的字典 (dictA) 的问题
我有一本字典,比如 dictA = {'a':'10', 'b':'20', 'c':'30'}
,我有一个 ObjectIdentifier('n')
的列表,其中 n
是一个数字。创建 dictB
的最佳方法是什么,以便 dictB
是一个 key 等于 dictA
的 的新字典key:value 对和 value 等于列表中相应的 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'}
因为字典没有顺序。
你可以这样创建你的字典:
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)'}}