简体   繁体   中英

Compare two dictionaries keys and create dictionary with list values in Python

Let's say you have two different dictionaries.

info_stored = {'a' : 0, 'b' : 2, 'c' : 15}

log_stored = {'dog' : 1, 'a' : 1, 'ted' : 14}

I want to compare these 2 dictionaries to determine if keys are matched. Only 'a' is common in this example.

for key in info_stored:
    if key in log_stored:

I want to create a new dictionary with the common key and a list of the values from that common key.

common_stored = {'a' : [0, 1]}

How about this:

info_stored = {'a' : 0, 'b' : 2, 'c' : 15}

log_stored = {'dog' : 1, 'a' : 1, 'ted' : 14}

common_stored = {k: [] for k in info_stored if k in log_stored}

and then:

for key in common_stored:
    common_stored[k].extend([info_stored[k], log_stored[k]])
print(common_stored)  # common_stored = {'a' : [0, 1]}

The first step is about creating a dictionary with the common elements as keys and empty lists as values.

Finally we modify these empty lists based on the contents of the original dicts.

You can even combine the two steps in a single dictionary comprehension as follows:

common_stored = {k: [info_stored[k], log_stored[k]] for k in info_stored if k in log_stored}
info_stored = {'a' : 0, 'b' : 2, 'c' : 15}
log_stored = {'dog' : 1, 'a' : 1, 'ted' : 14}

common_stored = {}

# Traverse through info_stored dictionary
for key, val in info_stored.items():
   # Check for key in log_stored dictionary, if found add it to common_stored
   if key in log_stored:
      common_stored[key] = [val, log_stored[key]]

common_stored
{'a': [0, 1]}

a simple solution would be this:

info_stored = {'a' : 0, 'b' : 2, 'c' : 15}

log_stored = {'dog' : 1, 'a' : 1, 'ted' : 14}

result={}


for key in info_stored :
  if key in log_stored :
    result[key]=[ info_stored[key], log_stored[key]]

print (result)

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