Home > Software engineering >  Adding new key, values to dictionaries within a list from a list
Adding new key, values to dictionaries within a list from a list

Time:10-21

Task : I have to generate some random date of births and add it to my list of three dictionaries. I have generated the random task but i am stuck with adding 'date of birth' keys to the dictionaries inside ducks with values from the list that i created. any suggestions plz? this is the code i have so far:

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

CodePudding user response:

Here you can use zip to iterate over both containers. It will allow you to take both iterables and return it as a tuple. Those values can simply be used in a normal for loop. You should note that this assumes both ducks and dob have the same size.

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

CodePudding user response:

Without the use of a generator and allowing for the ducks list being any length and with an pseudo-random date of birth generator that will only produce valid dates, you could do this:

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)

In the unlikely event that the random selection of year, month and day creates something invalid, datetime.strptime will raise ValueError so we just try again

CodePudding user response:

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])
    
    
  • Related