添加唯一字典列表

时间:2017-01-20 14:27:49

标签: python list dictionary

我有一个字典列表,如果它们不在列表中,我想在该列表中添加更多字典。

akka{
  remote.netty.tcp.port = 0
  cluster.auto-down-unreachable-after = 20s
  cluster.seed-nodes = ["akka.tcp://mySys@127.0.0.1:2552"]
  cluster.roles.1 = "someActor"
  actor.provider = "akka.cluster.ClusterActorRefProvider"
}

但是,如果我添加第二,第三和第四个词典条目,我最终会...

listofdictionary= []
newdictionary = {'Id': '001', 'Name': 'book title'}

for mydict in self.listofdictionary:
    if mydict['Id'] == newdictionary['Id']:
        print("Match for {0}".format(neworder['Title']))
    elif mydict['Id'] != newdictionary['Id']:
        self.listofdictionary.append(newdictionary)

谢谢,

约翰。

1 个答案:

答案 0 :(得分:2)

您的代码会检查列表中的所有词典,对于每个的词典使用不同的Id,它会附加新词典。

因此,如果列表中已有四个不同Id的词典,则会添加四次。

取而代之的是

if all(olddict['Id'] != newdictionary['Id'] for olddict in self.listofdictionary):
   self.listofdictionary.append(newdictionary)

if newdictionary['Id'] not in [d['Id'] for d in self.listofdictionary]:
   self.listofdictionary.append(newdictionary)

如果它实际上是词典的 dict ,那么事情会更容易:

if newdictionary['Id'] not in self.dictofdictionaries:
    self.dictofdictionaries[newdictionary['Id']] = newdictionary

或者使用多个字段来检查唯一性:

key = tuple(newdictionary[k] for k in ('Id', 'author', 'subject', 'etc'))

if key not in self.dictofdictionaries:
    self.dictofdictionaries[key] = newdictionary