繁体   English   中英

从列表向列表中的字典添加新键、值

[英]Adding new key, values to dictionaries within a list from a list

任务:我必须生成一些随机的出生日期并将其添加到我的三个字典列表中。 我已经生成了随机任务,但我坚持将“出生日期”键添加到鸭子内的字典中,并使用我创建的列表中的值。 有什么建议吗? 这是我到目前为止的代码:

ducks =[{'first_name': 'Davey', 'last_name': 'McDuck', 'location': "Rob's Office", 'insane': True, 'followers': 12865, 'following': 120, 
  'weapons': ['wit', 'steely stare', 'devilish good looks'], 'remorse': None}, 
 {'first_name': 'Jim', 'last_name': 'Bob', 'location': 'Turing Lab', 'insane': False, 'followers': 123, 
  'following': 5000, 'weapons': ['squeak'], 'remorse': None}, 
 {'first_name': 'Celest', 'last_name': '', 'location': 'Throne Room', 'insane': True, 'followers': 40189, 'following': 1, 
  'weapons': ['politics', 'dance moves', 'chess grandmaster', 'immortality']}] #list with three dictionaries
import random
dob = []
def dateofbirth(number=1):
    Year = random.randrange(1990, 2010)
    for item in range(number):
        yield random.randrange(1990, 2010), random.randrange(1, 12), random.randrange(1, 30)

dateTimeThatIwant = dateofbirth(3)
#print(dateTimeThatIwant)

for year, month, date in dateTimeThatIwant:
    #print((year, month, date))
    dob.append([year, month, date])
print(dob)
for d in ducks:
    d["dob"] = dob_value

在这里,您可以使用zip来遍历两个容器。 它将允许您采用两个可迭代对象并将其作为元组返回。 这些值可以简单地用于普通的 for 循环。 您应该注意,这假设ducksdob具有相同的大小。

ducks =[{'first_name': 'Davey', 'last_name': 'McDuck', 'location': "Rob's Office", 'insane': True, 'followers': 12865, 'following': 120, 
  'weapons': ['wit', 'steely stare', 'devilish good looks'], 'remorse': None}, 
 {'first_name': 'Jim', 'last_name': 'Bob', 'location': 'Turing Lab', 'insane': False, 'followers': 123, 
  'following': 5000, 'weapons': ['squeak'], 'remorse': None}, 
 {'first_name': 'Celest', 'last_name': '', 'location': 'Throne Room', 'insane': True, 'followers': 40189, 'following': 1, 
  'weapons': ['politics', 'dance moves', 'chess grandmaster', 'immortality']}] #list with three dictionaries
import random
dob = []
def dateofbirth(number=1):
    Year = random.randrange(1990, 2010)
    for item in range(number):
        yield random.randrange(1990, 2010), random.randrange(1, 12), random.randrange(1, 30)

dateTimeThatIwant = dateofbirth(3)
#print(dateTimeThatIwant)

for year, month, date in dateTimeThatIwant:
    #print((year, month, date))
    dob.append([year, month, date])
print(dob)
for c_dob, d in zip(dob, ducks):
    d['dob'] = c_dob

如果不使用生成器并允许鸭子列表具有任何长度并且使用仅生成有效日期的伪随机出生日期生成器,您可以这样做:

from datetime import datetime
from random import randint

ducks = [{'first_name': 'Davey', 'last_name': 'McDuck', 'location': "Rob's Office", 'insane': True, 'followers': 12865, 'following': 120,
          'weapons': ['wit', 'steely stare', 'devilish good looks'], 'remorse': None},
         {'first_name': 'Jim', 'last_name': 'Bob', 'location': 'Turing Lab', 'insane': False, 'followers': 123,
          'following': 5000, 'weapons': ['squeak'], 'remorse': None},
         {'first_name': 'Celest', 'last_name': '', 'location': 'Throne Room', 'insane': True, 'followers': 40189, 'following': 1,
          'weapons': ['politics', 'dance moves', 'chess grandmaster', 'immortality']}]


def randomdate(loyear=1990, hiyear=2010):
    while True:
        try:
            yy = randint(loyear, hiyear)
            mm = randint(1, 12)
            dd = randint(1, 31)
            datetime.strptime(f'{dd}/{mm}/{yy}', '%d/%m/%Y')
            return [yy, mm, dd]
        except ValueError:
            pass


for duck in ducks:
    duck['dob'] = randomdate()

print(ducks)

万一年、月和日的随机选择产生无效的结果,datetime.strptime 将引发 ValueError,所以我们只需再试一次

ducks =[{'first_name': 'Davey', 'last_name': 'McDuck', 'location': "Rob's Office", 'insane': True, 'followers': 12865, 'following': 120, 
  'weapons': ['wit', 'steely stare', 'devilish good looks'], 'remorse': None}, 
 {'first_name': 'Jim', 'last_name': 'Bob', 'location': 'Turing Lab', 'insane': False, 'followers': 123, 
  'following': 5000, 'weapons': ['squeak'], 'remorse': None}, 
 {'first_name': 'Celest', 'last_name': '', 'location': 'Throne Room', 'insane': True, 'followers': 40189, 'following': 1, 
  'weapons': ['politics', 'dance moves', 'chess grandmaster', 'immortality']}] #list with three dictionaries
import random
dob = []
def dateofbirth(number=1):
    Year = random.randrange(1990, 2010)
    for item in range(number):
        yield random.randrange(1990, 2010), random.randrange(1, 12), random.randrange(1, 30)

dateTimeThatIwant = dateofbirth(3)
#print(dateTimeThatIwant)

for year, month, date in dateTimeThatIwant:
    #print((year, month, date))
    dob.append([year, month, date])
print(dob)
for i,d in enumerate(ducks):
    d["dob"]=d.get("dob",dob[i])
    
    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM