I have two dictionaries. Like this:
d1 = {A: 1, B:2, C:3}
d2 = {1: xx, 2:xxx, 3:xxxx}
I wrote a code to compare both:
for k, v in d1.iteritems():
for l, m in d2.iteritems():
if l == v:
print k+'\t'+v+'\t'+m
And print as a table like this:
A 1 xx
B 2 xxx
C 3 xxxx
Suggestions like to create a new_dictionary is accepted.
for k, v in d1.iteritems():
if v in d2:
print('{}\t{}\t{}'.format(k, v, d2[v]))
"Suggestions like to create a new_dictionary is accepted."
print {key : [d1[key], d2[d1[key]]] for key in d1 if d1[key] in d2 }
for k, v in d1.items():
print(k, v, d2[v])
This is how to do it in Python 3.
Try this : simple and easy.
for i in d1:
if d1[i] in d2:
print i,d1[i],d2[d1[i]]
Related
I have a dictionary contains lists of values and a list:
dict={'first':45, 'second':30, 'third':56}
list= [30,45]
I want to compare the value in the dictionary with the list and a match to add to a new dictionary after that, remove from the old dict all the values that are in the new dict: I'm doing something like this:
def get_sessions(self, talks):
result_sessions = {}
for k, v in self.sessions.items():
for i in talks:
if v == i:
result_sessions[k] = v
for k, v in result_sessions.items():
del self.sessions[k]
return result_sessions
Maybe you know a more elegant solution? any help?
This is one approach.
Ex:
d ={'first':45, 'second':30, 'third':56}
lst = [30,45]
result_sessions = {k: v for k, v in d.items() if v in lst}
d = { k : d[k] for k in set(d) - set(result_sessions) }
print(result_sessions)
print(d)
Output:
{'second': 30, 'first': 45}
{'third': 56}
Suppose I have simple dictionary like this:
d = {'k1':'v1', 'key2':'val2'}
How can I render key, value lines in pystache using that dictionary?
You have to transform your dictionary a bit. Using the mustache syntax, you can only iterate through lists of dictionaries, so your dictionary d has to become a list where each key-value pair in d is a dictionary with the key and value as two separate items, something like this:
>>> [{"k": k, "v": v} for k,v in d.items()]
[{'k': 'key2', 'v': 'val2'}, {'k': 'k1', 'v': 'v1'}]
Complete sample program:
import pystache
tpl = """\
{{#x}}
- {{k}}: {{v}}
{{/x}}"""
d = {'k1':'v1', 'key2':'val2'}
d2 = [{"k": k, "v": v} for k,v in d.items()]
pystache.render(tpl, {"x": d2})
Output:
- key2: val2
- k1: v1
You could also use tuples, a bit less verbose:
import chevron
tpl = """\
{{#x}}
- {{0}}: {{1}}
{{/x}}"""
d = {'k1':'v1', 'key2':'val2'}
d2 = [(k, v) for k,v in d.items()]
print(chevron.render(tpl, {"x": d2}))
I have two dicts, that share the same keys but have distinct values. Each value is a set like this:
d1 = {'a': set(["a","b","c"]), 'b': set(["x","y","c"])}
d2 = {'a': set(["a","b","yu"]), 'b': set(["x","y","ri"])}
I would like to create a new dict, d3 that contains the same keys as d1 and d2, but with values that are the result of update each set of d1[key] with d2[key], I would like to do this inside a dict comprehension, something like:
d3 = {k: d1[k].update(d2[k]) for k in d1}
However, the result of:
d1[k].update(d2[k])
Of course is None, and I get a dict like:
d3 = {'a':None, 'b':None}
Any ideas?
update is the in-place version. The method that returns a new set and leaves the original unchanged is union; alternatively, you can use the | operator
d3 = {k: d1[k].union(d2[k]) for k in d1}
# or
d3 = {k: d1[k] | d2[k] for k in d1}
Is this what you want? I'm not sure
d3 = {k: d1[k] | d2[k] for k in d1}
This is what my code looks like thus far:
Given dictionaries, d1 and d2, create a new dictionary with the following property: for each entry (a, b) in d1, if there is an entry (b, c) in d2, then the entry (a, c) should be added to the new dictionary.
For example, if d1 is {2:3, 8:19, 6:4, 5:12} and d2 is {2:5, 4:3, 3:9}, then the new dictionary should be {2:9, 6:3}
Associate the new dictionary with the variable d3
d3 ={}
for i in d1:
for i in d2:
if d1.get(i,default=none) in d2:
d3[d1] = d2.get(i,default = None)
Python can express this beautifully. Too bad it's homework and you probably can't use dict comprehensions or whatever other limitations your "teacher" gives you
>>> d1 = {2:3, 8:19, 6:4, 5:12}
>>> d2 = {2:5, 4:3, 3:9}
>>> d3 = {a:d2[b] for a, b in d1.items() if b in d2}
>>> d3
{2: 9, 6: 3}
For Python2.5 or Python2.6 use a generator expression with dict()
d3 = dict((a, d2[b]) for a, b in d1.items() if b in d2)
For 2.4 see #KP's answer
Or, if you like one-liners:
d3 = dict([(k, d2[v]) for k, v in d1.items() if v in d2])
Given two dictionaries, d1 and d2, and an integer l, I want to find all keys k in d1 such that either d2[k]<l or k not in l. I want to output the keys and the corresponding values in d2, except if d2 does not contain the key, I want to print 0. For instance, if d1 is
a: 1
b: 1
c: 1
d: 1
and d2 is
a: 90
b: 89
x: 45
d: 90
and l is 90, the output would be (possibly in a different order)
b 89
c 0
What is the best way to do this in Python? I am just starting to learn the language, and so far this is what I have:
for k in d1.keys():
if k not in d2:
print k, 0
else:
if d2[k]<l:
print k, d2[k]
This works of course (unless I have a typo), but it seems to me that there would be a more pythonic way of doing it.
Yours is actually fine -- you could simplify it to
for k in d1:
if d2.get(k, 0) < l:
print k, d2.get(k, 0)
which is (to me) pythonic, and is pretty much a direct "translation" into code of your description.
If you want to avoid the double lookup, you could do
for k in d1:
val = d2.get(k, 0)
if val < l:
print k, val
You can simplify this by using a defaultdict. Calling __getitem__ on a defaultdict will return the "default" value.
from collections import defaultdict
d = defaultdict(int)
print d['this key does not exist'] # will print 0
Another bit that you could change is not to call keys. The dictionary implements iter. It would be preferable to simply write:
for k in d1:
Here is a compact version, but yours is perfectly OK:
from collections import defaultdict
d1 = {'a': 1, 'b': 1, 'c': 1, 'd': 1}
d2 = {'a': 90, 'b': 89, 'x': 45, 'd': 90}
l = 90
# The default (==0) is a substitute for the condition "not in d2"
# As daniel suggested, it would be better if d2 itself was a defaultdict
d3 = defaultdict(int, d2)
print [ (k, d3[k]) for k in d1 if d3[k] < l ]
Output:
[('c', 0), ('b', 89)]
Yours is good enough but here's one that is a little simpler:
for k in d1:
val = d2.get(k, 0)
if val < l:
print k, val