简体   繁体   中英

Python 2.7 - Two lists as dictionary

dict1 = open('dict1.txt','r')
dict2 = open('dict2.txt','r')

keys = []
values = []

for w in dict1:
   keys.append(w.strip())
   for key in keys:
       key


for x in dict2:
    values.append(x.strip())
    for val in values:
       val

dictionary = {key: val}

Text files contain 140 lines of single words. 'keys' is a list of words from the first file, 'values' is a list of words from the second file.

Whenever I print the dictionary, I get only the first pair. How to loop it inside dictionary so I get all 140 pairs?

I've tried doing this:

dictionary = {}
val = dictionary[key]

But I get 'KeyError' on the console. I know this is basic stuff but I've been struggling with it.

You can easily build the dictionary using zip :

for w in dict1:
   keys.append(w.strip())

for x in dict2:
    values.append(x.strip())

dictionary = dict(zip(keys, values))

Your KeyError is due to the assignment being the wrong way around:

val = dictionary[key]

tries to assign what is currently in dictionary for the key (which is nothing) to val . Instead, it should be:

dictionary[key] = val 

Your looping code is incorrect too:

for w in dict1:
   keys.append(w.strip())
   for key in keys: # looping over all keys so far each time
       key # doesn't do anything

And your first attempt:

dictionary = {key: val}

would create a new dictionary each time.

Use zip() to combine the keys and values from the two files. You can produce the whole dictionary in one go with just two lines of code:

with open('dict1.txt','r') as keys, open('dict2.txt','r') as values:
    dictionary = {key.strip(): value.strip() for key, value in zip(keys, values)}

Your code loops over the two files and after each loop, key and value are bound still to the last value of each iteration.

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