Creating and populating a new dictionary with entries from old - python

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_)

Related

How can I get my function to return more than 1 result (with for-loops and dictionaries) in Python?

I am trying to find a way to return more than one result for my dictionary in Python:
def transitive_property(d1, d2):
'''
Return a new dictionary in which the keys are from d1 and the values are from d2.
A key-value pair should be included only if the value associated with a key in d1
is a key in d2.
>>> transitive_property({'one':1, 'two':2}, {1:1.0})
{'one':1.0}
>>> transitive_property({'one':1, 'two':2}, {3:3.0})
{}
>>> transitive_property({'one':1, 'two':2, 'three':3}, {1:1.0, 3:3.0})
{'one':1.0}
{'three': 3.0}
'''
for key, val in d1.items():
if val in d2:
return {key:d2[val]}
else:
return {}
I've come up with a bunch of different things but they would never pass a few test cases such as the third one (with {'three':3}). This what results when I test using the third case in the doc string:
{'one':1.0}
So since it doesn't return {'three':3.0}, I feel that it only returns a single occurrence within the dictionary, so maybe it's a matter of returning a new dictionary so it could iterate over all of the cases. What would you say on this approach? I'm quite new so I hope the code below makes some sense despite the syntax errors. I really did try.
empty = {}
for key, val in d1.items():
if val in d2:
return empty += key, d2[val]
return empty
Your idea almost works but (i) you are returning the value immediately, which exits the function at that point, and (ii) you can't add properties to a dictionary using +=. Instead you need to set its properties using dictionary[key] = value.
result = {}
for key, val in d1.items():
if val in d2:
result[key] = d2[val]
return result
This can also be written more succinctly as a dictionary comprehension:
def transitive_property(d1, d2):
return {key: d2[val] for key, val in d1.items() if val in d2}
You can also have the function return a list of dictionaries with a single key-value pair in each, though I'm not sure why you would want that:
def transitive_property(d1, d2):
return [{key: d2[val]} for key, val in d1.items() if val in d2]
If return is used to , then the function is terminated for that particular call . So if you want to return more than one value it is impossible. You can use arrays instead .You can store values in array and the return thhe array.

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.

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

modify a dictionary

I need to modify a dictionary. I have a dictionary with integer values and want to replace each value with the fraction of the total of all values, eg.:
census={a:4, b:1, c:3}; turnIntoFractions(census), should then print {a:0.5, b:0,125 ,c:0,375 }
I was thinking something like:
def turnIntoFractions:
L=d.keys()
total=sum(L)
F=[]
for count in L:
f.append(float(count/float(total))
return F
I'm kind of stuck, and it isn't working..
You can use dictionary comprehension.
def turnIntoFractions(d):
total = float(sum(d.values()))
return {key:(value/total) for key,value in d.items()}
Your first problem is that you are doing the sum of the keys, not the values:
total = sum(d.values())
Now, you can just modify the dictionary inline, instead of putting it into a new list:
for key in d.keys():
d[key] /= total # or d[key] = d[key] / total
My previous code goes through each key, retrieves the value, then divides by total, and then finally stores it back into d[key].
If you want a new dictionary returned, instead of just modifying the existing one, you can just start out with e = d.copy(), then use e instead.
You seem to want to edit the dict in place, but your code returns a new object, which is actually better practice.
def turnIntoFractions(mydict):
values=d.values()
total=float(sum(values))
result = {}
for key, val in mydict.items():
result[key] = val/total
return result
your code has the right idea, but also a few small mistakes.
here's a working code:
def turnIntoFractions(d):
L=d.values()
total=sum(L)
f=[]
for count in L:
f.append(float(count/float(total)))
return f
census={'a':4, 'b':1, 'c':3}
print(turnIntoFractions(census))
note that python is case sensitive so f is not the same as F, and also keys that are strings need to be quoted
Use dictionary comprehension
sum = float(sum(census.itervalues()))
newDict = {k : (v / sum) for k,v in census.iteritems()}
for python 2.6:
newDict = dict((k,v /sum) for (k,v) in census.iteritems())
The following Python code will modify the dictionary's keys to float values.
def turnIntoFractions(mydict):
total = sum(mydict.values())
for key in mydict:
mydict[key] = float(mydict[key]) / total

How to print a dictionary's key?

I would like to print a specific Python dictionary key:
mydic = {}
mydic['key_name'] = 'value_name'
Now I can check if mydic.has_key('key_name'), but what I would like to do is print the name of the key 'key_name'. Of course I could use mydic.items(), but I don't want all the keys listed, merely one specific key. For instance I'd expect something like this (in pseudo-code):
print "the key name is", mydic['key_name'].name_the_key(), "and its value is", mydic['key_name']
Is there any name_the_key() method to print a key name?
Edit:
OK, thanks a lot guys for your reactions! :) I realise my question is not well formulated and trivial. I just got confused because I realised 'key_name' and mydic['key_name'] are two different things and I thought it would be incorrect to print the 'key_name' out of the dictionary context. But indeed I can simply use the 'key_name' to refer to the key! :)
A dictionary has, by definition, an arbitrary number of keys. There is no "the key". You have the keys() method, which gives you a python list of all the keys, and you have the iteritems() method, which returns key-value pairs, so
for key, value in mydic.iteritems() :
print key, value
Python 3 version:
for key, value in mydic.items() :
print (key, value)
So you have a handle on the keys, but they only really mean sense if coupled to a value. I hope I have understood your question.
Additionally you can use....
print(dictionary.items()) #prints keys and values
print(dictionary.keys()) #prints keys
print(dictionary.values()) #prints values
Hmm, I think that what you might be wanting to do is print all the keys in the dictionary and their respective values?
If so you want the following:
for key in mydic:
print "the key name is" + key + "and its value is" + mydic[key]
Make sure you use +'s instead of ,' as well. The comma will put each of those items on a separate line I think, where as plus will put them on the same line.
dic = {"key 1":"value 1","key b":"value b"}
#print the keys:
for key in dic:
print key
#print the values:
for value in dic.itervalues():
print value
#print key and values
for key, value in dic.iteritems():
print key, value
Note:In Python 3, dic.iteritems() was renamed as dic.items()
The name of the key 'key_name' is 'key_name', therefore
print('key_name')
or whatever variable you have representing it.
In Python 3:
# A simple dictionary
x = {'X':"yes", 'Y':"no", 'Z':"ok"}
# To print a specific key (for example key at index 1)
print([key for key in x.keys()][1])
# To print a specific value (for example value at index 1)
print([value for value in x.values()][1])
# To print a pair of a key with its value (for example pair at index 2)
print(([key for key in x.keys()][2], [value for value in x.values()][2]))
# To print a key and a different value (for example key at index 0 and value at index 1)
print(([key for key in x.keys()][0], [value for value in x.values()][1]))
# To print all keys and values concatenated together
print(''.join(str(key) + '' + str(value) for key, value in x.items()))
# To print all keys and values separated by commas
print(', '.join(str(key) + ', ' + str(value) for key, value in x.items()))
# To print all pairs of (key, value) one at a time
for e in range(len(x)):
print(([key for key in x.keys()][e], [value for value in x.values()][e]))
# To print all pairs (key, value) in a tuple
print(tuple(([key for key in x.keys()][i], [value for value in x.values()][i]) for i in range(len(x))))
Since we're all trying to guess what "print a key name" might mean, I'll take a stab at it. Perhaps you want a function that takes a value from the dictionary and finds the corresponding key? A reverse lookup?
def key_for_value(d, value):
"""Return a key in `d` having a value of `value`."""
for k, v in d.iteritems():
if v == value:
return k
Note that many keys could have the same value, so this function will return some key having the value, perhaps not the one you intended.
If you need to do this frequently, it would make sense to construct the reverse dictionary:
d_rev = dict(v,k for k,v in d.iteritems())
Update for Python3: d.iteritems() is not longer supported in Python 3+ and should be replaced by d.items()
d_rev = {v: k for k, v in d.items()}
# highlighting how to use a named variable within a string:
mapping = {'a': 1, 'b': 2}
# simple method:
print(f'a: {mapping["a"]}')
print(f'b: {mapping["b"]}')
# programmatic method:
for key, value in mapping.items():
print(f'{key}: {value}')
# yields:
# a 1
# b 2
# using list comprehension
print('\n'.join(f'{key}: {value}' for key, value in dict.items()))
# yields:
# a: 1
# b: 2
Edit: Updated for python 3's f-strings...
Make sure to do
dictionary.keys()
rather than
dictionary.keys
import pprint
pprint.pprint(mydic.keys())
Or you can do it that manner:
for key in my_dict:
print key, my_dict[key]
dict = {'name' : 'Fred', 'age' : 100, 'employed' : True }
# Choose key to print (could be a user input)
x = 'name'
if x in dict.keys():
print(x)
What's wrong with using 'key_name' instead, even if it is a variable?
Probably the quickest way to retrieve only the key name:
mydic = {}
mydic['key_name'] = 'value_name'
print mydic.items()[0][0]
Result:
key_name
Converts the dictionary into a list then it lists the first element which is the whole dict then it lists the first value of that element which is: key_name
I'm adding this answer as one of the other answers here (https://stackoverflow.com/a/5905752/1904943) is dated (Python 2; iteritems), and the code presented -- if updated for Python 3 per the suggested workaround in a comment to that answer -- silently fails to return all relevant data.
Background
I have some metabolic data, represented in a graph (nodes, edges, ...). In a dictionary representation of those data, keys are of the form (604, 1037, 0) (representing source and target nodes, and the edge type), with values of the form 5.3.1.9 (representing EC enzyme codes).
Find keys for given values
The following code correctly finds my keys, given values:
def k4v_edited(my_dict, value):
values_list = []
for k, v in my_dict.items():
if v == value:
values_list.append(k)
return values_list
print(k4v_edited(edge_attributes, '5.3.1.9'))
## [(604, 1037, 0), (604, 3936, 0), (1037, 3936, 0)]
whereas this code returns only the first (of possibly several matching) keys:
def k4v(my_dict, value):
for k, v in my_dict.items():
if v == value:
return k
print(k4v(edge_attributes, '5.3.1.9'))
## (604, 1037, 0)
The latter code, naively updated replacing iteritems with items, fails to return (604, 3936, 0), (1037, 3936, 0.
I looked up this question, because I wanted to know how to retrieve the name of "the key" if my dictionary only had one entry. In my case, the key was unknown to me and could be any number of things. Here is what I came up with:
dict1 = {'random_word': [1,2,3]}
key_name = str([key for key in dict1]).strip("'[]'")
print(key_name) # equal to 'random_word', type: string.
Try this:
def name_the_key(dict, key):
return key, dict[key]
mydict = {'key1':1, 'key2':2, 'key3':3}
key_name, value = name_the_key(mydict, 'key2')
print 'KEY NAME: %s' % key_name
print 'KEY VALUE: %s' % value
key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])
If you want to get the key of a single value, the following would help:
def get_key(b): # the value is passed to the function
for k, v in mydic.items():
if v.lower() == b.lower():
return k
In pythonic way:
c = next((x for x, y in mydic.items() if y.lower() == b.lower()), \
"Enter a valid 'Value'")
print(c)

Categories