I've been trying to learn Python and have come across this issue. I can't figure out how the current output came about.
d={'k1':1,'k2':2,'k3':3}
for key,value in d.keys() :
print(key)
Output:
k
k
k
I expected the output to be:
k1
k2
k3
You are trying to print all key, value pair from your dictionary d. But you are only able to see first character of the key when you try to print key. I will explain you by splitting your for loop for key,value in d.keys().
This is your dictionary, d
d = {'k1':1,'k2':2,'k3':3}
The for loop takes d.keys() and iterates. d.keys() look like this
print(d.keys()) # outputs dict_keys(['k1', 'k2', 'k3'])
for loop iterates over this list of keys ['k1', 'k2', 'k3']
But when you do, this
key,value = 'k1' # this happens with each of the keys in the list
print(key,value) # output k 1
Your key k1 got split into two single character strings k and 1 which can be termed as an unintentional tuple creation #inquisitiveOne and gets assigned to key and value variables respectively.
When you try to print value inside the for loop, you will see 1, 2, 3 but that is in fact the second character of the key attribute and not the value attribute. If you try printing, print(type(value)) you will get to know that it is in fact a string variable and not an integer.
To get the proper value of the key you need to only use a single variable.
d={'k1':1,'k2':2,'k3':3}
for key in d.keys():
print(key)
Output:
k1
k2
k3
As mentioned by #asikorski you can achieve the same using just for key in d: print(key)
If you need to get key, value pairs. Then use d.items()
for key,value in d.items():
print(key,value)
Output:
k1 1
k2 2
k3 3
Hope it helps!
d.keys() returns ['k1', 'k2', 'k3'], but you split that into two parts with key, value, so key=='k', value=='1' the first time, and key=='k', value=='2' the second time, and so on. What you want is:
for key in d.keys():
print(key)
But you can do better and iterate directly over the dictionary without using the .keys() method:
for key in d:
print(key)
Finally, if you need to use both keys and values:
for key, values in d.items():
print(key)
print(value)
d.keys() is a list and it's value will be ["k1", "k2", "k3"]
>> d.keys()
["k1", "k2", "k3"]
When you use for key,value in d.keys(), unpacking will happen on the string value. Which means from "k1", "k" will be assigned to key and "1" will be assigned to value.
Luckily it didn't give error because there were only 2 characters in the string.
>> key, value = "k1"
>> key
k
>> value
1
And, that is the reason it printed k k k in console.!
The right way is to iterate through k.items()
for key,value in d.items():
print(key,value)
Output
k1 1
k2 2
k3 3
d={'k1':1,'k2':2,'k3':3}
for key in d.keys() :
print(key)
Try this code, this should work.
for getting the keys you need the keys API:
d={'k1':1,'k2':2,'k3':3}
for key in d.keys() :
print(key)
for getting the values use the values API:
d={'k1':1,'k2':2,'k3':3}
for value in d.values() :
print(value)
for getting keys and values there is the items API:
d={'k1':1,'k2':2,'k3':3}
for key,value in d.items() :
print(key)
print(value)
hope it helps
Answer is unintentional tuple creation.
In the statement:
for key,value in d.keys() :
you are creating a tuple unintentionally.
>>> key, value = "k1"
>>> key
'k'
>>> value
'1'
Note that the brackets are optional for creating a tuple.
The above is the same as:
>>> (key, value) = "k1"
>>> key
'k'
>>> value
'1'
>>>
Hence the output.
The problem is in your for loop:
for key,value in d.keys() :
d.keys() is an iterable (technically a dict_keys object) that contains only the keys of d: k1, k2, and k3.
Your for loop unpacks each string into k (represented by key) and a number (represented by value). You then print only key, which in each instance is k.
To remedy the issue, simply stop unpacking the keys:
for key in d.keys():
Related
I need to inverse a dictionary so that each old value will now be a key and the old keys will be the new values.
The trick is that there could be multiple values that are the same in the old dictionary so I need each value in the new dictionary to be a list, and if there were identical values in the old dictionary then they both will be in the list of the value of the new dictionary.
for example:
the dictionary {"python" : 1, "is" : 1, "cool" : 2}
would end up as: {1 : ["python", "is"], 2 : ["cool"]}
this is what I tried:
def inverse_dict(my_dict):
new_dict = {}
values_list = list(my_dict.values())
new_dict = new_dict.fromkeys(values_list)
for key in new_dict:
new_dict[key] = []
for old_key in my_dict:
new_dict[my_dict[old_key]] = list(new_dict[my_dict[old_key]]).append(old_key)
return new_dict
Would greatly appreciate any help with my approach (and better approaches to the problem) as I am very new to Python, thanks!
You can use dict.setdefault check if a key exists in the dictionary and if not, create new value (in this case empty list []):
d = {"python" : 1, "is" : 1, "cool" : 2}
reversed_d = {}
for k, v in d.items():
reversed_d.setdefault(v, []).append(k)
print(reversed_d)
Prints:
{1: ['python', 'is'], 2: ['cool']}
This can be more explicitly rewritten as:
d = {"python" : 1, "is" : 1, "cool" : 2}
reversed_d = {}
for k, v in d.items():
if v not in reversed_d:
reversed_d[v] = [k]
else:
reversed_d[v].append(k)
print(reversed_d)
You can use a defaultdict to avoid the pre-fill step
from collections import defaultdict
def inverse_dict(my_dict: dict):
new_dict = defaultdict(list)
for k, v in my_dict.items():
new_dict[v].append(k)
return new_dict
Though I prefer #azro's answer with the default dict, another solution is doing it with dictionary and list comprehensions.
It looks like this:
{value : [key for key in my_dict if my_dict[key] == value] for value in set(my_dict.values())}
What it does is runs over the values of the dictionary without duplicates - set(my_dict.values()).
It builds every value as a key (because it's on the left side of the ":").
And its value is a list of the keys that point to that value - [key for key in my_dict if my_dict[key] == value].
Say that we have two dictionaries:
d1={'A':['a','b','c'],'B':['d','e']}
d2={'a':3,'b':1,'c':1,'d':2,'e':0}
And that we need to compute a third dictionary that has the same keys as d1, and for values the sum of the values in d2 that correspond to those keys that are, in turn, values ind1.
Example:
d3={'A':5,'B':2}
where 5 is assigned to A because it is the sum of the values of a,b,c, which are assigned to A in d1.
My attempt:
d3={key:sum(d2[i] for i in d1[j] for j in d1.keys()) for key in d1.keys()}
returns:
NameError: global name 'j' is not defined
Sorry for the trivial question, but what am I missing here?
It's simpler than that if you use dict.items():
d3 = {key: sum(d2[v] for v in val) for key, val in d1.items()}
d3 = {}
for k,v in d1.items():
d3[k] = sum([ d2[x] for x in v ])
d1={'A':['a','b','c'],'B':['d','e']}
d2={'a':3,'b':1,'c':1,'d':2,'e':0}
dict(zip(d1.keys(), map(lambda x:sum(d2.get(i) for i in x[1]), d1.items())))
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))
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.
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