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}
Related
Let's assume that there's a dictionary variable 'dict' like below. with tuple type keys in this case.
dict = {(a,2019): 6, (a,2020): 7 , (a,2021):8, (a,2022):9, (b,2020):8, (b,2021):10}
And then I want to search all values with keys that has 'a' for the first element of the key.
So after search I want to put the result set into a list 'result'. result will have the values like below.
result = [6,7,8,9]
I would be able to get values like below
result.append(dict.get((a,2019)))
result.append(dict.get((a,2020)))
....
but I wanted to search data by matching only once for example using regex in this case like
result=dict.get((a, "\d{4}"))
Obviously, this doesn't work.
I just want to know if there's a way that I can search data by matching only one element of tuple type keys in this case.
You may just want a dictionary of dictionaries. If you define:
from collections import defaultdict
mydict = defaultdict(dict)
Then you can write things like mydict['a'][2010] = 100 and have what you expect.
Looking at the value of mydict['a'] will returns dictionary of all years in which the first part of the key is 'a'.
How about a list comprehension to see if a is in the key of you dictionary?
mydict = {(a,2019): 6, (a,2020): 7 , (a,2021):8, (a,2022):9, (b,2020):8, (b,2021):10}
result = [v for k,v in mydict.items() if a in k]
# [6, 7, 8, 9]
You can use list comprehension:
dct = {('a',2019): 6, ('a',2020): 7 , ('a',2021):8, ('a',2022):9, ('b',2020):8, ('b',2021):10}
result = [v for k, v in dct.items() if k[0] == 'a']
print(result) # [6, 7, 8, 9]
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}
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 need a structure for my little Python program to save a list of max 500 names with one number each. The names would be unique, but the numbers would repeat (often). I first thought of a dictionary, but I also need to be able to search for the numbers, for instance I would need to change all 2 to 3. What would you recommend?
I am new to Python, so I am sure I overlooked a simple solution.
("Spiderman",1)
("Dr. House",2)
("Jon Skeet",1)
You can use a dict, and search by value like so:
names = {"Spiderman":1, "Dr. House":2, "Jon Skeet":1}
resulting_keys = [k for k, v in names.iteritems() if v == 1]
# returns ['Spiderman', 'Jon Skeet']
Then you can do something like:
names.update(dict((k,names[k] + 1) for k in resulting_keys))
Which will now update names to:
{'Jon Skeet': 2, 'Dr. House': 2, 'Spiderman': 2}
Dictionary would work. If you need to change the stored values:
>>> d = {"SpiderMan":1, "Dr.House":2, "Jon Skeet":1}
>>> for k,v in d.items():
... if v == 1:
... d[k] = v+1
...
...
...
>>> d
{'SpiderMan': 2, 'Dr.House': 2, 'Jon Skeet': 2}
It's going to be a linear search (O(n)). Do you need better than that?