I have a list of codes
l = [1, 2, 3, 4]
And a dictionary of previously seen codes and their translation
d = {1: 'A', 2: 'B', 3: 'C' }
I am trying to compare the list values to the dict key and create a new dict with the dict values of the matches. I accomplished this with the code below:
x = {k: d[k] for k in l if k in d}
However I also want to keep the list values that don't appear in the existing dict because these it is important to track new values. I would like to store these in the new dict with the val being 'no match' or something. I am not sure how to do this in a pythonic way.
Final dict:
{1: 'A', 2: 'B', 3: 'C', 4: 'no match'}
I know that this can be done by creating a dataframe from the dictionary and a dataframe from the list & outer joining but I would like to get better at dictionaries if possible!
You can use dict.get(), which can take a default value that is returned in case the key is not found in the dictionary:
x = {k: d.get(k, 'no match') for k in l}
Related
I'm using Aiohttp's implementation of multidict().
Take this:
>>> d = MultiDict[('a', 1), ('b', 2), ('a', 3)])
>>> d
<MultiDict {'a': 1, 'b': 2, 'a': 3}>
I want to convert d to a regular dictionary where duplicate key values are appended into a list such as this:
{'a': [1, 3], 'b': 2}
Is there an elegant way to convert this? Other than a loop through items and a lot of logical conditions?
It doesnt look like multidicts have an inbuilt function for a straight conversion, but you can use the .keys() function to iterate through the multidict and copy the values into a fresh dictionary.
new_dict = {}
for k in set(multi_dict.keys()):
new_dict[k] = multi_dict.getall(k)
Two interesting things here - we need to make a set of the multidict keys function call to remove duplicates, and multidicts have a .getall() function that returns a list of all values associated with duplicate keys.
EDIT for single value cases:
new_dict = {}
for k in set(multi_dict.keys()):
k_values = multi_dict.getall(k)
if len(k_values) > 1:
new_dict[k] = k_values
else:
new_dict[k] = k_values[0]
I know that there are a bunch of ways to make a dictionary out of two lists, but I wanted to do it using two FOR loops to iterate over both lists. Therefore, I used the following code. Surprisingly, the code doesn't iterate over the second list that contains the values of the dictionary keys and only considers the last element of the list as the value.
key = ['hello', 'mello', 'vello']
value = [1, 2, 3]
dictionary = {k: v for k in key for v in value}
print('dictionary is ', dictionary)
the result was:
dictionary is: {'hello': 3, 'mello': 3, 'vello': 3}
But I expect that the result would be:
dictionary is: {'hello': 1, 'mello': 2, 'vello': 3}
I appreciate it if anyone can clarify this for me.
My understanding is the full dictionary is being recreated each loop with each number as the key, resulting in only your final output being that of the last value (best shown by reversing your key and value statements, returning {1: 'vello', 2: 'vello', 3: 'vello', 4: 'vello'}
If the other is your intended output, this should work fine:
dictionary = dict(zip(key,value))
You can use zip for this purpose.
dictionary = dict(zip(keys, values))
I am new to Python so I do apologize that my first question might not be asked clearly to achieve the right answer.
I thought if I converted a list with duplicating keys into a dictionary then I would be able to sum the values of each duplicating key. I have tried to search on Google and Stack Overflow but I actually still can't solve this problem.
Can anybody help, please? Thank you very much in advance and I truly appreciate your help.
list1 = ["a:2", "b:5", "c:7", "a:8", "b:12"]
My expected output is:
dict = {a: 10, b: 17, c: 7}
You can try this code:
list1 = ["a:2", "b:5", "c:7", "a:8", "b:12"]
l1 = [each.split(":") for each in list1]
d1 = {}
for each in l1:
if each[0] not in d1:
d1[each[0]] = int(each[1])
else:
d1[each[0]] += int(each[1])
d1
Output: {'a': 10, 'b': 17, 'c': 7}
Explanation:
Step 1. Convert your given list to key-value pair by splitting each of the elements in your original list from : and store that in a list/tuple
Step 2. Initialize an empty dictionary
Step 3. Iterate through each key-value pair in the newly created list/tuple and store that in a dictionary. If the key doesn't exist, then add new key-value pair to dictionary or else just add the values to it's corresponding key.
A list does not have "keys" per say, rather it has elements. In your example, the elements them selves are a key value pair. To make the dictionary you want you have to do 3 things,
Parse each element into its key value pair
Handle duplicate values
Add each pair to the dictionary.
the code should look like this
list1 = ["a:2", "b:5", "c:7", "a:8", "b:12"]
dict1={}#make an empty dictionary
for element in list1:
key,value=element.split(':')#This splits your list elements into a tuple of (key,value)
if key in dict1:#check if the key is in the dictionary
dict1[key]+=int(value)#add to existing key
else:
dict1[key]=int(value)#initilize new key
print(dict1)
That code prints out
{'a': 10, 'c': 7, 'b': 17}
You could use a defaultdict, iterate over each string and add the corresponding value after splitting it to a pair (key, value).
>>> from collections import defaultdict
>>> res = defaultdict(int)
>>> for el in list1:
... k, v = el.split(':')
... res[k]+=int(v)
...
>>> res
defaultdict(<class 'int'>, {'a': 10, 'b': 17, 'c': 7})
I have not found a solution to my question, yet I hope it's trivial.
I have two dictionaries:
dictA:
contains the order number of a word in a text as key: word as value
e.g.
{0:'Roses',1:'are',2:'red'...12:'blue'}
dictB:
contains counts of those words in the text
e.g.
{'Roses':2,'are':4,'blue':1}
I want to replace the values in dictA by values in dictB via keys in dictB, checking for nones, replacing by 0.
So output should look like:
{0:2,1:4,2:0...12:1}
Is there a way for doing it, preferentially without introducing own functions?
Use a dictionary comprehension and apply the get method of dict B to return 0 for items that are not found in B:
>>> A = {0:'Roses',1:'are',2:'red', 12:'blue'}
>>> B = {'Roses':2,'are':4,'blue':1}
>>> {k: B.get(v, 0) for k, v in A.items()}
{0: 2, 1: 4, 2: 0, 12: 1}
With three list variables (all different sizes) and a list comprehension:
indexesA=[1,2,3,4,5]
indexesB=['a','b','c','d']
values=['Dog','Cat','Sheep','Donkey','Horse']
keys=[2,3,'d']
print [values[indexesA.index(key)] for key in keys if key in indexesA and indexesA.index(key)<len(values)]
I need to get a dictionary:
{2: 'Cat', 3: 'Sheep', 'd': 'Donkey'}
indexesA list should be checked if key among its values first. If not then check indexesB.
How to achieve this?
Edited:
Please note that the list comprehension I posted in my question is only checking indexesA for the key. The code is incomplete.
print [values[indexesA.index(key)] for key in keys if key in indexesA and indexesA.index(key)<len(values)]
This is one way to do it using list-comprehensions
>>> keys = [2, 3, 'd']
>>> {k: values[indexesA.index(k) if k in indexesA else indexesB.index(k)] for k in keys if (k in indexesA) or (k in indexesB)}
{2: 'Cat', 3: 'Sheep', 'd': 'Donkey'}
>>>
Disclaimer: This code is neither readable, maintainable or extendable.