python dictionary with repetition of key and value - python

I have two array as follows:
a=['history','math','history','sport','math']
b=['literature','math','history','history','math']
I zipped two arrays and used dictionary to see if key and values are equal print me them but the dictionary did not print the cases which are repeated, it print only one one them and i need all of them because I need the number of time they are repeated.
My code:
combined_dict={}
for k , v in zip(a,b):
combined_dict[k]=v
print(combined_dict)

In dictionaries, there are no duplicate keys. So when you have {'history':'literature'} after the first loop, it will get overriden with {'history':'history'}.
Instead of creating a dictionary, why not just loop through the zip(a, b)?
for k, v in zip(a, b):
if k == v:
print(k, v)
If you want to have multiple values for one key, then you can use a defaultdict from the collections module:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for k, v in zip(a, b):
... d[k].append(v)
...
>>> print(d)
defaultdict(<type 'list'>, {'sport': ['history'], 'math': ['math', 'math'], 'history': ['literature', 'history']})
>>> print(list(d.items()))
[('sport', ['history']), ('math', ['math', 'math']), ('history', ['literature', 'history'])]
>>> for k, v in d.items():
... if k in v:
... print k, v
...
math ['math', 'math']
history ['literature', 'history']

A dict cannot have the same key for two entries. For multiple values with same key, you need a dict with a list as value.
Try this:
from collections import defaultdict
a=['history','math','history','sport','math']
b=['literature','math','history','history','math']
combined_dict = defaultdict(list)
for k, v in zip(a,b):
combined_dict[k].append(v)
print combined_dict

If you want to get a list of all the items, where there is a match between the two lists, try
>>> print [k for k, v in zip(a, b) if k == v]
['math', 'history', 'math']
This gives you a list of matching items, which you can then process further.

Related

How to reverse dictionary items and list keys grouped by common values [duplicate]

This question already has answers here:
Dictionary comprehension for swapping keys/values in a dict with multiple equal values
(3 answers)
Closed 2 years ago.
I have a dictionary that I want to group by the common values:
init_dict = {'00001': 'string1', '00002': 'string2', '00003': 'string1', '00004': 'string3', '00005': 'string2'}
I want to create a new dictionary that groups the values and lists the keys like this:
new_dict = {'string1': ['00001', '00003'], 'string2':['00002', '00004'], 'string3': ['00004']}
I tried many things and this is the closest I can get.
lookup = 'string1'
all_keys = []
for k, v in init_dict.items():
if v == lookup:
all_keys.append(k)
print(all_keys)
This produces the first list: ['00001', '00003'] so I thought I could somehow loop through a list of lookup values but can't since I'm working with strings. Is there a way to do this and is there a way that is relatively efficient because my initial dictionary has 53,000 items in it. Any help would be much appreciated as I've been trying different things for hours.
Use a defaultdict, specifying a list as default argument, and append the corresponding values from the dictionary:
from collections import defaultdict
d = defaultdict(list)
for k,v in init_dict.items():
d[v].append(k)
print(d)
defaultdict(list,
{'string1': ['00001', '00003'],
'string2': ['00002', '00005'],
'string3': ['00004']})
You can use defaultdict
result = defaultdict(list)
for k, v in init_dict.items():
result[v].append(k)
or itertools.groupby
result = {k: [x[0] for x in v] for k, v in
groupby(sorted(init_dict.items(), key=lambda kv: kv[1]), key=lambda kv: kv[1])}
You can also use a normal dict (instead of defaultdict):
new_dict = {}
for key, val in init_dict.items():
if val in new_dict:
new_dict[val].append(key)
else:
new_dict[val] = []
new_dict[val].append(key)
Output:
new_dict = {'string1': ['00001', '00003'],
'string2': ['00002', '00005'],
'string3': ['00004']}

compare values from a list with values from a dictionary

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}

Convert a list of dictionaries to a dictionary using dict constructor

I have the code snippet below that I want to get a dictionary from a list of dictionaries but getting global name item not found error. Wondering if it is possible to enumerate like below
l = [{1:{'item1':'value1'}},{2:{'item2':'value2'}}]
dic = dict(((k,v)) for k,v in item.items() for item in l)
print dic
You have your for ... in ... clauses backwards. They should go in the same order as if they were normal for-loops:
>>> l = [{1:{'item1':'value1'}},{2:{'item2':'value2'}}]
>>> dic = dict(((k,v)) for item in l for k,v in item.items())
>>> dic
{1: {'item1': 'value1'}, 2: {'item2': 'value2'}}
>>>
Also, I would like to point out that in Python 2.6+, you can use a dict comprehension for this:
>>> l = [{1:{'item1':'value1'}},{2:{'item2':'value2'}}]
>>> dic = {k:v for item in l for k,v in item.items()}
>>> dic
{1: {'item1': 'value1'}, 2: {'item2': 'value2'}}
>>>
Your ordering of the statements is wrong. Think of it in the way that you would order it in a normal loop. So, for item in l comes first and then for k, v in item.items().
>>> dic = dict(((k,v)) for item in l for k,v in item.items())
>>> dic
{1: {'item1': 'value1'}, 2: {'item2': 'value2'}}
Now, the comprehension becomes
for item in l:
for k, v in item.items():
# Do Something
instead of
for k, v in item.items():
for item in l:
# Do Something
which is an error.
list comprehension for's are interpreted just like a normal for loop(which actually is somewhat counter intuitive) so what you have is
for k,v in item.items():
for item in mylist:
k,v
surely you can see the problem with that
first refer to ques How to create single Python dict from a list of dicts by summing values with common keys?
It will help you to analyse your problem.....now thhink of normal loops...
>>> dic = dict(((k,v)) for item in l for k,v in item.items())
>>> dic
{1: {'item1': 'value1'}, 2: {'item2': 'value2'}}
then handled as....
for item in l:
for k, v in item.items():

How do I loop over a map object's 2ND value in reverse?

I have a map and I am using a for loop to loop through it, but it only gives me the first value,.in ascending order. Any help appreciated!
What do you mean by ascending order? You could sort them:
Python 2.7
for v in sorted(map.itervalues()):
print v
Python 3
for v in sorted(map.values()):
print v
If instead you wanted keys to be sorted, try:
for _, v in sorted(map.items()):
print v
I'm assuming that by map you mean a dict, by "first value" you mean key, and by "second value" you mean value?
You can use .iteritems() to iterate over key/value pairs instead of just keys
d = {'a': 1, 'b': 2}
for k, v in d.iteritems():
print "key:", k
print "value:", v
Or .itervalues() to iterate over just the values:
for v in d.valueitems():
print "value:", v
There's no way to apply ordering to a dict's items directly -- iteration over a dict can occur in any order. You can however iterate over a sorted iteritems():
for k, v in sorted(d.iteritems(), key=lambda k, v: v):
print "key:", k
print "value:", v
Or just the values:
for v in sorted(d.valueitems()):
print "value:", v
It's not very clear what your asking, but I took my best guess. Next time try to post some of your already done code!
>>> mydict = {'a': 1, 'b': 89, 'c': 56, 'd': 9123, 'e':-23}
>>> mylist = []
>>> for k in mydict:
... mylist.append(mydict[k])
...
>>> mylist.sort()
>>> mylist.reverse()
>>> mylist
[9123, 89, 56, 1, -23]
>>>
Explanation:
Lines
Set mydict to some value of numbers (because you want it in reverse)
Set mylist to a blank list
Loop over the first value of the dict
Use the first value to get the second value with mydict[k].
Append that to mylist
Use mylist.sort() to sort in ascending order
Use mylist.reverse() to reverse it.

Sorting keys of same values alphabetically

I have a dictionary where I want to alphabetically sort the keys that have the same value assigned to them.
For example: {chai:1, apple:1, dom banana:1}
How do I sort these keys alphabetically?!
Thanks.
>>> from collections import defaultdict
>>> items = {'chai':1, 'apple':1, 'dom banana':1}
>>> d = defaultdict(list)
>>> for k,v in items.iteritems():
d[v].append(k)
>>> {k:sorted(v) for k,v in d.iteritems()}
{1: ['apple', 'chai', 'dom banana']}
sorted(k for k,v in D.iteritems() if v == 1)

Categories

Resources