Home > Enterprise >  i have multiple dictionaries in a python list. i want to find what they share in values & then compa
i have multiple dictionaries in a python list. i want to find what they share in values & then compa

Time:12-24

ok so here's an example dataset:

returntime= '9:00'


data1 = {Name:'jim', cardriven: '20123', time:'7:30'}
data1 = {Name:'bob', cardriven: '20123', time:'10:30'}
data1 = {Name:'jim', cardriven: '201111', time:'8:30'}
data1 = {Name:'bob', cardriven: '201314', time:'9:30'}

my problem is that i need to be able to loop over these dictionaries & find the car that both of them have driven & then compare the times they drove them to see who returned the car closest to 9:00

i have tried many loops & created lists etc... but i know theres gotta be a simple way to just say...

for [data1, data2....] who returned the car closest to the time... and here is the info from that record.

thanx in advance

CodePudding user response:

Maybe you can trying using only 1 dict where each entry in the dict is another dict with the key being maybe the name of the driver or an ID code.
Then you can loop over that dict and find out which dict entries had driven the same car.

Here's a simplified example of what I mean

returntime= '9:00'


data1 = {'Name':'jim', 'cardriven': '20123', 'time': "7:30"}
data2 = {'Name':'bob', 'cardriven': '20123', 'time': "10:30"}
data3 = {'Name':'jim', 'cardriven': '201111', 'time': "8:30"}

dict = {}
dict[0] = data1
dict[1] = data2
dict[2] = data3


for i in range(len(dict)):
    if dict[i]["cardriven"] == '20123':
        print(dict[i]["Name"])

Output:

jim
bob

Also a pro-tip: you can enter the time into the dict as a datetime object and that would help you greatly in comparing the time.

CodePudding user response:

This will iterate through the data you offered and put cars in a dictionary, which will keep track of whichever car has the closest time to the goal.

import datetime

returntime = "09:00"

data = [
    dict(name="Jim", cardriven="20123", time="7:30"),
    dict(name="Bob", cardriven="20123", time="10:30"),
    dict(name="Jim", cardriven="201111", time="8:30"),
    dict(name="Bob", cardriven="201314", time="9:30"),
]

def parsedelta(s):
    t = datetime.datetime.strptime(s, "%M:%S")
    return datetime.timedelta(minutes=t.minute, seconds=t.second)

deltareturn = parsedelta(returntime)

def diffreturn(s):
    return abs(deltareturn.seconds - parsedelta(s).seconds)

cars = {}
for datum in data:
    car = datum["cardriven"]
    if car not in cars:
        cars[car] = datum
        continue
    if diffreturn(datum["time"]) < diffreturn(cars[car]["time"]):
        cars[car] = datum

print(cars)
  • Related