简体   繁体   中英

Printing Matching Keys Python

I have a list of dictionaries

d = [{"Date": "2020/10/03 3:30", "Name": "John"}, {"Date": "2020/10/03 5:15", "Name": "Harry"}, {"Date": "2020/10/05 6:30", "Name": "Rob"}]

and I want to only print the name with the same dates.

Output:
John
Harry

I am not sure how I can implement this, any tips ?

Your problem can easily be solved by traversing the list of entries and collecting the dates with the names in a new dictionary. So, you use the dates as key for a dictionary and add the names in a corresponding list of that date. I'm adding a code snippet that does that fairly easily:

d = [{"Date": "2020/10/03 3:30", "Name": "John"}, {"Date": "2020/10/03 5:15","Name": "Harry"}, {"Date": "2020/10/05 6:30", "Name": "Rob"}]

dates = {}

for entry in d:
    date = entry["Date"].split()[0]
        if date in dates:
            dates[date].append(entry["Name"])
        else:
            dates[date] = []
            dates[date].append(entry["Name"])

print(dates["2020/10/03"])
print(dates["2020/10/05"])

Yes, I know my code snippet doesn't directly provide your specified output. I kept it open ended so you can tailor it towards your specific needs.

Here's an approach using collections.Counter and a couple list comprehensions:

from collections import Counter

d = [{"Date": "2020/10/03 3:30", "Name": "John"}, {"Date": "2020/10/03 5:15", "Name": "Harry"}, {"Date": "2020/10/05 6:30", "Name": "Rob"}]

dates = Counter([obj['Date'].split()[0] for obj in d])
multiples = [val for val in dates.keys() if dates[val] > 1]

for obj in d:
    if obj['Date'].split()[0] in multiples:
        print(obj['Name'])

This prints the following output:

John
Harry

You can extract dates and then sort and group by them.

from datetime import datetime
from itertools import groupby

This is a helper function for extracting the date from a dictionary:

def dategetter(one_dict):
    return datetime.strptime(one_dict['Date'], 
                             "%Y/%m/%d %H:%M").date()

This is a dictionary comprehension that extracts, sorts, groups, and organizes the results into a dictionary. You can print the dictionary data in any way you want.

{date: [name['Name'] for name in names] for date,names 
       in groupby(sorted(d, key=dategetter), key=dategetter)}
#{datetime.date(2020, 10, 3): ['John', 'Harry'], 
# datetime.date(2020, 10, 5): ['Rob']}

Assuming the "Date" format is consistent, you can use simple dict & list comprehensions:

from collections import defaultdict

res = defaultdict(list)

for i in d:
    dt = i["Date"].split()[0]
    res[dt].append(i["Name"])

for date, names in res.items():
    if len(names) > 1:
        print(*names, sep="\n")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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