附加到列表中的所有词典

时间:2016-01-13 05:10:08

标签: python dictionary

我有一个列表back_populates。里面有很多字典。我必须为所有人添加一个键值class Puppy(Base): __tablename__ = "puppy" id = Column(Integer, primary_key=True, nullable=False) name = Column(String(80)) adopters = relationship('Adopter', secondary="puppy_adopters", back_populates="puppies") class Adopter(Base): __tablename__ = "adopter" id = Column(Integer, primary_key=True, nullable=False) name = Column(String) puppies = relationship('Puppy', secondary="puppy_adopters", back_populates="adopters") puppy_adopters = Table('puppy_adopters', Base.metadata, Column('puppy_id', Integer, ForeignKey('puppy.id')), Column('adopter_id', Integer, ForeignKey('adopter.id'))) Rex = Puppy(name='Rex') Fido = Puppy(name='Fido') Bob = Adopter(name='Bob') Steve = Adopter(name='Steve') Steve.puppies.append(Fido) Bob.puppies.append(Fido) Bob.puppies.append(Rex) print [adopter.name for adopter in Fido.adopters] # ['Steve', 'Bob'] print [puppy.name for puppy in Bob.puppies] # ['Fido', 'Rex']

这是我的方法:

all

还有另一种方法可以更快地完成吗?

2 个答案:

答案 0 :(得分:0)

如果您希望所有词典的时间一致,请使用

a = [{'name':"sadness",'calss':'A1'},{'name':'joy','class':'B1'},{'name':'mark','class':'C1'}]
import datetime
c={'datetime':datetime.datetime.now()}
for d in a:
    d.update(c)
print a

答案 1 :(得分:0)

由于您的数据本质上是表格式的,因此您可以使用pandas.DataFrame

import pandas as pd
df = pd.DataFrame(all)
df['datetime'] = datetime.datetime.now()
print df

如果你选择将其作为一个词典列表,我很担心你的循环是达到这个目标的唯一方法。

此外,all在python中不是一个好的变量名。

<强>计时

对于一个包含1M元素的大型列表,假设您将数据存储在一个数据框中,这个速度提高了8倍!

N = 1000000
all = [ {'a': 'a%s'%i, 'b':i} for i in range(N) ]
df = pd.DataFrame(all)

%timeit df['datetime'] = datetime.datetime.now()
100 loops, best of 3: 6.38 ms per loop
%timeit for d in all: d['datetime'] = now
10 loops, best of 3: 46.7 ms per loop

或者,重复调用now():

%timeit for d in all: d['datetime'] = datetime.datetime.now()
1 loops, best of 3: 597 ms per loop