[英]Most pythonic way to append Dictionary with specific keys
A dictionary like Dict = {'Key_1': 'Data_1', 'Key_2': 'Data_2', ..., 'Key_n': 'Data_n'}
contains n
keys named in ascending order. 类似
Dict = {'Key_1': 'Data_1', 'Key_2': 'Data_2', ..., 'Key_n': 'Data_n'}
包含n
以升序命名的键。
A method like AddNextKey(Dict, NewData)
should determine the last key n
and add a new one n+1
with value NewData
. 诸如
AddNextKey(Dict, NewData)
应确定最后一个键n
并添加一个值为NewData
的新n+1
。 If Dict
is empty, the method should append key Key_1
. 如果
Dict
为空,则该方法应附加键Key_1
。
I am quite sure that a pythonic solution does not require more than two or three lines of code to achieve this. 我非常确定,pythonic解决方案不需要超过两三行代码即可实现此目的。
Remark: It is not important that the dictionary is ordered. 备注:订购字典并不重要。 Only the correct next key (n+1) must be appended.
只有正确的下一个键(n + 1)必须附加。
Could anybody give advice? 有人可以提供建议吗?
I'm not sure if it's the most Pythonic solution but my approach is to subclass dict
and add that additional method. 我不确定这是否是最Pythonic的解决方案,但我的方法是将
dict
子类化并添加该其他方法。 Since it's a subclass, you can use an instance of NextKeyDict
anywhere you could an actual dict
, but also perform these special operations where needed. 由于它是子类,因此您可以在实际可以使用
dict
任何地方使用NextKeyDict
的实例,还可以在需要时执行这些特殊操作。
class NextKeyDict(dict):
def add_next_key(self, new_data):
if not self.keys():
self[0] = new_data
return
last_key = sorted(self.keys())[-1]
new_key = last_key + 1
self[new_key] = new_data
d = NextKeyDict()
d.add_next_key('foo')
d.add_next_key('bar')
d.add_next_key('baz')
print(d)
Output 输出量
{0: 'foo', 1: 'bar', 2: 'baz'}
You could use the length of the dictionary 您可以使用字典的长度
Dict = dict()
for i in range(10):
Dict['key_' + str(len(Dict)+1)] = 'value_'+str(len(Dict)+1)
print Dict
Outputs 产出
{'key_10': 'value_10', 'key_5': 'value_5', 'key_4': 'value_4', 'key_7': 'value_7', 'key_6': 'value_6', 'key_1': 'value_1', 'key_3': 'value_3', 'key_2': 'value_2', 'key_9': 'value_9', 'key_8': 'value_8'}
There is no order in a dictionary. 字典中没有顺序。 And you can not get the last inserted element from it.
而且您无法从中获取最后插入的元素。
Take a look at this example: 看一下这个例子:
>>> {'Key_1': 'Data_1', 'Key_2': 'Data_2'} == {'Key_2': 'Data_2', 'Key_1': 'Data_1'}
True
As you can see, the order is meaningless for the dict
. 如您所见,顺序对于
dict
毫无意义。
The question is what exactly do you mean by the last key n. 问题是最后一个键n到底是什么意思。 Last inserted?
最后插入? Or with biggest key_%index%?
还是具有最大的key_%index%? In first case you better to use OrderedDict, as already mentioned.
在第一种情况下,您最好使用OrderedDict,如前所述。
However, here is my solution, if I got you right. 但是,如果我答对了,这就是我的解决方案。
def AddNextKey(Dict, NewData):
Dict['Key_%d' % (len(Dict) + 1)] = NewData
d = {}
AddNextKey(d, 'Data_1')
AddNextKey(d, 'Data_2')
AddNextKey(d, 'Data_3')
print d
You will get 你会得到
{'Key_1': 'Data_1', 'Key_3': 'Data_3', 'Key_2': 'Data_2'}
Normal Python dictionaries are unordered. 普通的Python字典是无序的。 So technically, there is no "last" key.
因此,从技术上讲,没有“最后”键。
But there is a way around that. 但是有一种解决方法。 You could use the
len
method to see how many items there are in the dictionary, and construct the next key based on that. 您可以使用
len
方法查看字典中有多少个项目,并根据该项目构造下一个键。
But note that this method is fragile . 但是请注意,这种方法很脆弱 。 if you accidentally add a key 'foo' to the dictionary, your whole scheme is off.
如果您不小心在字典中添加了键“ foo”,则整个方案都将关闭。
To really fix this you would have to create a subclass of dict
(by overriding the __setitem__
and update
methods as shown in this answer ) so that it only accepts valid keys in the form 'Key_N'
. 要真正解决此问题,您将必须创建
dict
的子类(通过覆盖__setitem__
和update
方法(如本答案所示)),以便它仅接受格式为'Key_N'
有效键。 You could then also add an append
method to automatically create the next key. 然后,您还可以添加一个
append
方法来自动创建下一个键。
But as turbulencetoo commented, it would probably be easier to use a list. 但是正如turbulencetoo所说,使用列表可能会更容易。
# set-up the dictionary for demo purposes
testdict = {x:y for x,y in zip(["Key_"+str(x) for x in range(1,7)],
["Data_"+str(x) for x in range(1,7)])}
# fetch most recent key
# add 1 to recent_key_val and insert new value
if len(testdict) != 0:
recent_key_val = max([int(x.split("_")[1]) for x in testdict])
testdict["Key_"+str(recent_key_val +1)] = "New_Data"
else:
testdict["Key_1"] = "New_Data"
Something you need is already built into Python. 您需要的东西已经内置在Python中。 So I think the most pythonic way is to use OrderedDict.
因此,我认为最有效的方法是使用OrderedDict。 As the docs say
正如文档所说
Return an instance of a dict subclass, supporting the usual dict methods.
返回支持常规dict方法的dict子类的实例。 An OrderedDict is a dict that remembers the order that keys were first inserted.
OrderedDict是可以记住首次插入键的顺序的字典。 If a new entry overwrites an existing entry, the original insertion position is left unchanged.
如果新条目覆盖了现有条目,则原始插入位置将保持不变。 Deleting an entry and reinserting it will move it to the end.
删除条目并重新插入将其移至末尾。
from collections import OrderedDict
d = OrderedDict()
d["Key1"] = 1
d["Key2"] = 2
d["Key3"] = 3
last_key = d.keys()[-1] # "Key3" thanks to ordering
new_key = calculate_new_key(last_key)
d[new_key] = new_value
By definition, python dictionary are an unordered set of key: value pairs, with the requirement that the keys are unique. 根据定义,python字典是无序的一组键:值对,要求键必须唯一。 Given that you can use OrderedDict from class collections to create and update the dictionary and preserve the order.
假设您可以使用类集合中的OrderedDict创建和更新字典并保留顺序。
from collections import OrderedDict
d1 = OrderedDict([(1, 'Data_1'), (2, 'Data_2'),(3, 'Data_3')])
You get 你得到
OrderedDict([(1, 'Data_1'), (2, 'Data_2'), (3, 'Data_3')])
Now the method to update the dictionary 现在更新字典的方法
def AddNextKey(Dict, NewData):
last_key = next(reversed(Dict))
new_key = last_key + 1
Dict.update({new_key: NewData})
When you call 你打电话时
AddNextKey(d1, 'Blah')
You get 你得到
OrderedDict([(1, 'Data_1'), (2, 'Data_2'), (3, 'Data_3'), (4, 'Blah')])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.