Python 2.7 - Two lists as dictionary - python

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.

Related

a rather complicated case in filtering dictionaries

I have a dictionary such as:
{2:'r', 4:'y', 5:'u', 7:'y', 13:'r', 17:'y'}
and I want a list: for every duplicated value the first key with that value . so in this example I want
[2, 4]
We can use a new dictionary to reverse k and v:
d = {2:'r', 4:'y', 5:'u', 7:'y', 13:'r', 17:'y'}
new_dict = {}
for k,v in d.items():
new_dict[v] = new_dict.get(v, []) + [k]
Now we have a new dictionary whose keys are values of the original dictionary and values are lists containing keys from the original dictionary whose values are now the key of the new dictionary. Now we have to check if there are more than 1 element in values:
duplicates = []
for k,v in new_dict.items():
if len(v)>1:
duplicates.append(v[0])

Python: How to combine two dictionaries in python such that the resultant contains key as the value from the first

I have two dictionaries as follows:
mydictionary_1 = {1:'apple',2:'banana'}
mydictionary_2 = {1:50,2:30}
The resultant dictionary should be such that it takes the key as the value of first dictionary.
Result_dictionary= {'apple':50, 'banana':30}
You can use a dictionary comprehension using the values of the first dictionary as the keys of the resulting dictionary. This assumes all keys of the first are present in the second dict
{v: dict2[k] for k, v in dict1.items()}
you can also add a check for the presence of the keys in the second dictionary
{v: dictionary_2[k] for k, v in dictionary_1.items() if k in dictionary_2}
Loop through one of the dictionaries and check if the value for a key in mydictionary_1 exists in mydictionary_2.
You can achieve this using python's dictionary comprehension -
Result_dictionary = { v:mydictionary_2[k] for k,v in mydictionary_1.iteritems() if k in mydictionary_2.keys()}
To see how this list comprehension is working you can even use general for loop to loop through each key, value pair in mydictionary_1
for key,value in mydictionary_1.iteritems():
if key in mydictionary_2.keys():
Result_dictionary[value]=mydictionary_2[key]
Dictionary comprehension is an ideal solution for this one, as previously mentioned. Here is a for loop example:
def combine_dictionaries(dict1, dict2):
result_dictionary = {}
for key in dict1.keys():
result_dictionary[dict1[key]] = dict2[key]
return result_dictionary
combine_dictionaries({1:'apple', 2:'banana'}, {1:50, 2:30})
>>>{'apple': 50, 'banana': 30}
This assumes all values of the dict1 are present in the dict2.
def dict_cross_match(dict1, dict2):
new_dict = {}
for item in dict1.keys():
if item in dict2.keys():
new_dict[dict1[item]] = dict2[item]
return new_dict
mydictionary_1 = {1:'apple',2:'banana'}
mydictionary_2 = {1:50,2:30}
print(dict_cross_match(mydictionary_1, mydictionary_2))

Creating and populating a new dictionary with entries from old

def makeNewDictFromOld(oldDict):
newDict = {}
for key,value in oldDict.items():
if value compared to something else is true:
newDict[key].append(value)
return newDict
If I do this I get an error saying KeyError: last key of old dict.
Is there another way to do this?
You are trying to access a key that doesn't yet exist; your newDict is empty.
If you wanted to populate newDict with lists as the values, you need to first set the key to an empty list. Do so with dict.setdefault():
for key,value in oldDict.items():
if value compared to something else is true:
newDict.setdefault(key, []).append(value)
This sets key to [] first, unless the key is already present in the dictionary.
However, since all keys in the old dictionary are unique, you may as well just use:
for key,value in oldDict.items():
if value compared to something else is true:
newDict[key] = [value]
That is, unless you were entirely confused and just wanted to set the value directly, and not create lists:
for key,value in oldDict.items():
if value compared to something else is true:
newDict[key] = value
Last but not least, you could create the new dictionary entirely in a dictionary comprehension:
def makeNewDictFromOld(oldDict):
return {key: value for key, value in oldDict.items()
if value compared to something else is true}
Just do this instead of append
def makeNewDictFromOld(oldDict):
newDict = {}
for key,value in oldDict.items():
if True:
newDict[key] = value #assign directly instead of append
return newDict
dict_ = {"name":"name1","age":35}
print makeNewDictFromOld(dict_)

How can you print a key given a value in a dictionary for Python?

For example lets say we have the following dictionary:
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
How can you print a certain key given its value?
print(dictionary.get('A')) #This will print 4
How can you do it backwards? i.e. instead of getting a value by referencing the key, getting a key by referencing the value.
I don't believe there is a way to do it. It's not how a dictionary is intended to be used...
Instead, you'll have to do something similar to this.
for key, value in dictionary.items():
if 4 == value:
print key
In Python 3:
# A simple dictionary
x = {'X':"yes", 'Y':"no", 'Z':"ok"}
# To print a specific key (for instance the 2nd key which is at position 1)
print([key for key in x.keys()][1])
Output:
Y
The dictionary is organized by: key -> value
If you try to go: value -> key
Then you have a few problems; duplicates, and also sometimes a dictionary holds large (or unhashable) objects which you would not want to have as a key.
However, if you still want to do this, you can do so easily by iterating over the dicts keys and values and matching them as follows:
def method(dict, value):
for k, v in dict.iteritems():
if v == value:
yield k
# this is an iterator, example:
>>> d = {'a':1, 'b':2}
>>> for r in method(d, 2):
print r
b
As noted in a comment, the whole thing can be written as a generator expression:
def method(dict, value):
return (k for k,v in dict.iteritems() if v == value)
Python versions note: in Python 3+ you can use dict.items() instead of dict.iteritems()
target_key = 4
for i in dictionary:
if dictionary[i]==target_key:
print(i)
Within a dictionary if you have to find the KEY for the highest VALUE please do the following :
Step 1: Extract all the VALUES into a list and find the Max of list
Step 2: Find the KEY for the particular VALUE from Step 1
The visual analyzer of this code is available in this link : LINK
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
lis=dictionary.values()
print(max(lis))
for key,val in dictionary.items() :
if val == max(lis) :
print("The highest KEY in the dictionary is ",key)
I think this is way easier if you use the position of that value within the dictionary.
dictionary = {'A':4,
'B':6,
'C':-2,
'D':-8}
# list out keys and values separately
key_list = list(dictionary.keys())
val_list = list(dictionary.values())
# print key with val 4
position = val_list.index(4)
print(key_list[position])
# print key with val 6
position = val_list.index(6)
print(key_list[position])
# one-liner
print(list(my_dict.keys())[list(my_dict.values()).index(6)])
Hey i was stuck on a thing with this for ages, all you have to do is swap the key with the value e.g.
Dictionary = {'Bob':14}
you would change it to
Dictionary ={1:'Bob'}
or vice versa to set the key as the value and the value as the key so you can get the thing you want

Defining a list of values for a dictionary key using an external file

I have a file with a list of paired entries (keys) that goes like this:
6416 2318
84665 88
90 2339
2624 5371
6118 6774
And I've got another file with the values to those keys:
266743 Q8IUM7
64343 H7BXU6
64343 Q9H6S1
64343 C9JB40
23301 Q8NDI1
23301 A8K930
As you can see the same key can have more than one value. What I'm trying to do is creating a dictionary by automatically creating the initial k, v pair, and then append more values for each entry that is already in the dictionary, like this:
Program finds "266743: 'Q8IUM7'", then "64343: 'H7BXU6'". And when it finds "64343: 'Q9H6S1'" it does this: "64343: ['H7BXU6', 'Q9H6S1']".
This is what I have so far:
# Create dictionary
data = {}
for line in inmap:
value = []
k, v = [x.strip() for x in line.split('\t')]
data[k] = value.append(v)
if k in data.viewkeys() == True and v in data.viewvalues() == False:
data[k] = value.append(v)
But the if statement seems to not be working. That or having the value = [] inside the for loop. Any thoughts?
This is not a good idea. You should be using a list from the start and expand that list as you go along, not change from "string" to "list of strings" when more than one value is found for the key.
For this, you can simply use
from collections import defaultdict
data = defaultdict(list)
for line in inmap:
k, v = (x.strip() for x in line.split('\t'))
data[k].append(v)
This works because a defaultdict of type list will automatically create a key together with an empty list as its value when you try to reference a key that doesn't yet exist. Otherwise, it behaves just like a normal dictionary.
Result:
>>> data
defaultdict(<type 'list'>, {'23301': ['Q8NDI1', 'A8K930'],
'64343': ['H7BXU6', 'Q9H6S1', 'C9JB40'], '266743': ['Q8IUM7']})

Categories