I'm taking two lists of tuples, doing some calculations and creating a dictionary, or at least trying to, so that I can find the character with the largest percentage.
dict_original = dict(original_list)
for c, p in new_list:
if c in dict_original and dict_original[c] < p:
diff = p - dict_original[c]
output = {c:round(diff,3)}
print output
The output i'm getting is something like this:
{'o': 0.026}
{'x': 0.046}
{'t': 0.037}
{'/': 0.038}
{'p': 0.037}
{'s': 0.038}
All I want is the character with the largest percentage; 'x', in this case. I've been unsuccessful using max so far.
I know, my output seems to be a bunch of dictionaries, that's why i'm asking for some help here.
Thanks!
Without seeing your data it is hard to give you proper guidance.
You are not creating a new dictionary of all the results just a dict per result which is being discarded. You can create a complete dictionary using a dict comprehension, e.g. this is equivalent to your for loop:
do = dict_original
output = {c: round(p-do[c], 3) for c, p in new_list if do.get(c, float('inf')) < p}
To get the maximum value from this dict then as pointed out by #batman:
max(output, key=output.get)
Would return 'x'
You can pass max a key argument:
bar = max(foo, key=foo.get)
That will give you the key with the largest value.
Related
I'm a Python Newb and trying to create a dictionary with ordered values.
Since dict.fromkeys only allows me to copy the same value for each key, I've set all values to 0 and tried something like this:
def Ord_Values_in_Dic(D):
c = 0
for value in D.values():
c += 1
value += c
return D
My output only changes the first value of the dictionary to 1 though, instead I'd want the second value to also change to 2, the third value to change to 3 and so on...
I don't get if the loop isn't iterating correctly through the dictionary or there's something else wrong.
Since dict.fromkeys only allows me to copy the same value for each key
then it is not right tool for you task. You might use zip to prepare dict from 2 iterables - one for keys, one for values, consider following simple example
keys = ["x","y","z"]
d = dict(zip(keys,range(3)))
print(d) # {'x': 0, 'y': 1, 'z': 2}
range with single arguments gives subsequent numbers from 0 (inclusive) to given value (exclusive), so in above example: 0,1,2
Got it!
import numpy as np
a = np.linspace(0,100,100)
b = np.sin(a)
c = np.cos(a)
idx = list(range(1,101))
X = dict(zip(b, idx))
Y = dict(zip(c, idx))
This solved it!
Thank you :)
For example, my dictionary contain this:
a = {1:'a',3:'b',2:'c',4:'d',1:'e',4:'f'}
To sort key on that list, I can do this:
b = []
for m in a:
b.append(m)
b.sort()
for value in b:
print(a[value])
The problem is: 'd' and 'e' share the same value 4, and its only export one value. But I want to export all of them. How can I do that?
A dictionary is assigns a value to a key (or a key references a specific value). Therefore it is not possible to have a dictionary with the same key twice (check, what a looks like after assigning!).
What you may want to look at is a list of tuples!
a = [(1,'a'),(3,'b'),(2,'c'),(4,'d'),(1,'e'),(4,'f')]
After that, you can do the sorting just by doing this:
a.sort(key=lambda x: x[0])
Duplicate keys in a dictionary is not allowed. Your dict does not contain what you think.
>>> a = {1:'a',3:'b',2:'c',4:'d',1:'e',4:'f'}
>>> a
{1: 'e', 2: 'c', 3: 'b', 4: 'f'}
When initializing your dictionary, the key 4 is defined twice: 4:'d', 4:'f'.
The second value 'f' overwrites the 'd' stored at a[4]. This is by design and therefore, you would need to correct your implementation to take this behaviour into account.
I have a dictionary like this :
d = {'v03':["elem_A","elem_B","elem_C"],'v02':["elem_A","elem_D","elem_C"],'v01':["elem_A","elem_E"]}
How would you return a new dictionary with the elements that are not contained in the key of the highest value ?
In this case :
d2 = {'v02':['elem_D'],'v01':["elem_E"]}
Thank you,
I prefer to do differences with the builtin data type designed for it: sets.
It is also preferable to write loops rather than elaborate comprehensions. One-liners are clever, but understandable code that you can return to and understand is even better.
d = {'v03':["elem_A","elem_B","elem_C"],'v02':["elem_A","elem_D","elem_C"],'v01':["elem_A","elem_E"]}
last = None
d2 = {}
for key in sorted(d.keys()):
if last:
if set(d[last]) - set(d[key]):
d2[last] = sorted(set(d[last]) - set(d[key]))
last = key
print d2
{'v01': ['elem_E'], 'v02': ['elem_D']}
from collections import defaultdict
myNewDict = defaultdict(list)
all_keys = d.keys()
all_keys.sort()
max_value = all_keys[-1]
for key in d:
if key != max_value:
for value in d[key]:
if value not in d[max_value]:
myNewDict[key].append(value)
You can get fancier with set operations by taking the set difference between the values in d[max_value] and each of the other keys but first I think you should get comfortable working with dictionaries and lists.
defaultdict(<type 'list'>, {'v01': ['elem_E'], 'v02': ['elem_D']})
one reason not to use sets is that the solution does not generalize enough because sets can only have hashable objects. If your values are lists of lists the members (sublists) are not hashable so you can't use a set operation
Depending on your python version, you may be able to get this done with only one line, using dict comprehension:
>>> d2 = {k:[v for v in values if not v in d.get(max(d.keys()))] for k, values in d.items()}
>>> d2
{'v01': ['elem_E'], 'v02': ['elem_D'], 'v03': []}
This puts together a copy of dict d with containing lists being stripped off all items stored at the max key. The resulting dict looks more or less like what you are going for.
If you don't want the empty list at key v03, wrap the result itself in another dict:
>>> {k:v for k,v in d2.items() if len(v) > 0}
{'v01': ['elem_E'], 'v02': ['elem_D']}
EDIT:
In case your original dict has a very large keyset [or said operation is required frequently], you might also want to substitute the expression d.get(max(d.keys())) by some previously assigned list variable for performance [but I ain't sure if it doesn't in fact get pre-computed anyway]. This speeds up the whole thing by almost 100%. The following runs 100,000 times in 1.5 secs on my machine, whereas the unsubstituted expression takes more than 3 seconds.
>>> bl = d.get(max(d.keys()))
>>> d2 = {k:v for k,v in {k:[v for v in values if not v in bl] for k, values in d.items()}.items() if len(v) > 0}
There is one question I am working on and got a very close answer... basically, the question is that you get two dictionaries and you have to find elements that intersect from both dictionaries and then create those elements (one same key from both dicts and two values from both dics) in a new dictionary.
a = {'A':17,'B':31,'C':42,'D':7,'E':46,'F':39,'G':9}
b = {'D':8,'E':3,'F':2,'g':5}
def intersect(a,b):
c = set(a).intersection(set(b))
d = {}
for i in c:
if i in a:
d[i] = int(a[i]),int(b[i])
return d
OUTPUT: {'E': (46, 3), 'D': (7, 8), 'F': (39, 2)}
I want to get the output like {'E': 46, 3, 'D': 7, 8, 'F': 39, 2}
How do I get rid of the parentheses around the values?
The code as you have written won't output anything at all. However, if you want to remove parentheses, then you can use this.
str(intersect(a, b)).replace('(', '').replace(')', '')
or equivalently this, which is a bit more concise and efficient
str(intersect(a, b)).translate(None, '()')
The output you are seeing is the python representation of your dictionary. What you have built (and, as far as I can tell, you have built it correctly -- it's what you want) is a dictionary mapping keys to pairs of items. The pairs are tuples, and those get printed with parentheses around them.
It sounds like what you want is an method which takes your dictionary and prints it, formatted in a specific way.
Something like this would print the dictionary the way you want it to:
def dictionary_printer(d):
print "{%s}" % ', '.join(
[("'%s': %s" % (key, ', '.join(map(str,value))))
for key, value in d.items()]
)
I had a python dict like this:
{'1' : {'1': {'A' : 34, 'B' : 23, 'C' : nan, 'D': inf, ...} ....} ....}
For each "letter" key I had to calculate something, but I obtained values like inf or nan and I need to remove them. How could I do that?
My first tried was to "cut" such values, i.e., to return just values between 0 and 1000 but when I did this, I got a dict with empty values:
{'1' : {'1': {'A' : 34, 'B' : 23, 'C' : {}, 'D': {}, ...} ....} ....}
perhaps there is a better solution, please help!!!!
This is part of my code, (Q and L are other dict that have the info that I need to calculate):
for e in L.keys():
dR[e] = {}
for i in L[e].keys():
dR[e][i] = {}
for l, ivalue in L[e][i].iteritems():
for j in Q[e].keys():
dR[e][i][j] = {}
for q, jvalue in Q[e][j].iteritems():
deltaR = DeltaR(ivalue, jvalue) #this is a function that I create previously
if (0 < deltaR < 100):
dR[e][i][j] = deltaR
You should be able to use the del statement to delete the dictionary item. For example:
del dct['1']['1']['C']
I'm taking a shot in the dark here, but you can probably do it in a couple of different ways. One method would be to calculate the value and then decide whether or not you actually want to keep it before sticking it into the dictionary.
d = {}
for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
# I don't actually know how you're calculating values
# and it kind of doesn't matter
value = calculate(letter)
if value in (inf, nan):
continue
d[letter] = value
I'm simplifying the dictionary to only pay attention to the part of your data that actually uses letters as keys since you haven't really given any context. That being said, I'd probably go with the first suggestion unless there's a reason not to.
for e in L.keys():
dR[e] = {}
for i in L[e].keys():
dR[e][i] = {}
for l, ivalue in L[e][i].iteritems():
for j in Q[e].keys():
#dR[e][i][j] = {} # What's up with this? If you don't want an empty dict,
# just don't create one.
for q, jvalue in Q[e][j].iteritems():
deltaR = DeltaR(ivalue, jvalue) #this is a function that I create previously
if (0 < deltaR < 100):
dR[e][i][j] = deltaR
if dR[e][i][j] in (nan, inf):
del dR[e][i][j]