This question already has an answer here:
Nested dictionary from nested list
(1 answer)
Closed 4 years ago.
file2.txt file1.txt I have an initial dictionary like:
{'A':'B'}
I have two text file like:
file1.txt
B[
C1:
C2:
file2.txt
C1[
b1:
b2:
C2[
n1:
n2:
what i am trying is to do that i take string ending with '[' as key and string ending with ':' as value
file_directory = ['Desktop/input_file/file1.txt','Desktop/input_file/file2.txt']
now I am iterating through the list of a directory which contains some text file, and take the value of initial dictionary that is B and searching in each directory if I found the B I make it as key and taking all as value except B and the new dictionary will be like this:
{'A':{'B':{'C1','C2'}}}
and again iterate through the all director and searching for each value of key B if it is found again make it key and append its value and then the new dictionary will be like:
{'A':{'B':{'C1':{'b1',b2'},'C2':{'n1','n2'}}}}
and it goes in a similar way until we don't get any match for any value and if any value is not found in any directory ,take value as key and put its value as empty braces like I search for the value b1,b2,n1 and n2 and did not found it will look like:
{'A':{'B':{'C1':{'b1':{},'b2':{}},'C2':{'n1':{},'n2':{}}}}}
Your explanation does not really make sense; But if I have understood your question properly you mean the following:
# dict 'd' with one key, that has a value 'b'
d={'a': 'b'}
# dict c one key with value 2
c={'f': 2}
# appending c into d/ by creating a key 'b' that has dict c as a value
d['b']=c
#output
{'a': 'b', 'b': {'f': 2}}
# let's update the dictionary b in d by adding another key j in b
d['b']['j']= 'r'
# output
{'a': 'b', 'b': {'f': 2, 'j': 'r'}}
Related
I have two dict:
a={'a':'A','b':'B'}
b={'a':123,'b':123}
I need check if keys 'a' and 'b' (two elements in example, in real code, it will be more) in dict b, exist in dict a. If so, I should change the keys in dict b using values from dict a:
Expected result:
b={'A':123, 'B': 123}
How I can do it?
{a[k] if k in a else k: v for k, v in b.items()}
This is how it's done:
a={'a':'A','b':'B'}
b={'a':123,'b':123}
c = {}
for key in a.keys():
if key in b.keys():
c.update({a[key]:b[key]})
The other answers so far ignore the question which wants the code to:
change keys in dict in b for values from dict a
I infer that any data in b, for which there isn't a replacement key in a, should be left alone. So walking the keys of a creating a new dictionary c won't work. We need to modify b directly. A fun way to do this is via the pop() method which we normally associate with lists but also works on dictionaries:
a = {'a': 'A', 'b': 'B'}
b = {'a': 123, 'b': 124, 'C': 125}
for key in list(b): # need a *copy* of old keys in b
if key in a:
b[a[key]] = b.pop(key) # copy data to new key, remove old key
print(b)
OUTPUT
> python3 test.py
{'C': 125, 'A': 123, 'B': 124}
>
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})
This question already has answers here:
Is it possible to assign the same value to multiple keys in a dict object at once?
(8 answers)
Closed 3 years ago.
Is there a compact way to have alternative keys for the same value in a dictionary?
Taking a dictionary like the following
dict={'A':1,'B':2,'one':1,'two':2}
I can obtain the value 1 using two different keys:
dict['A']
dict['one']
I would like to know if there is a more compact way to write it, something akin to:
dict2={['A','one']:1,['B','two']:2}
You can define the dict with keys of the same value grouped as a tuple first:
d = {('A', 'one'): 1, ('B', 'two'): 2}
so that you can then convert it to the desired dict with:
d = {key: value for keys, value in d.items() for key in keys}
d becomes:
{'A': 1, 'one': 1, 'B': 2, 'two': 2}
I have the following two dictionaries
scores1={'a':10,'b':20,'c':30,'d':10} #dictionary holds value scores for a,b,c,d
and
scores2={'a':20,'b':10} #this dictionary only has scores for keys a and b
I need to collate and sum the scores for keys a and b in both dictionaries to produce the following output:
The answer could be 'done' using one of the following two methods (and there may be others I'd be interested to hear)
1. Using the creation of a new dictionary:
finalscores={a:30,b:30} #adds up the scores for keys a and b and makes a new dictionary
OR
2. update the scores2 dictionary (and add the values from scores1 to the scores2 corresponding respective values
An accepted answer would show both the above with any suitable explanation as well as suggest any more astute or efficient ways of solving the problem.
There was a suggestion on another SO answer that the dictionaries could simply be added:
print(scores1+scores2)
Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?
But I want to do this in the simplest method possible, without iterator imports or classes
I have also tried, but to no avail:
newdict={}
newdict.update(scores1)
newdict.update(scores2)
for i in scores1.keys():
try:
addition = scores[i] + scores[i]
newdict[i] = addition
except KeyError:
continue
For the first solution:
scores1={'a':10,'b':20,'c':30,'d':10} #dictionary holds value scores for a,b,c,d
scores2={'a':20,'b':10} #this dictionary only has scores for keys a and b
finalscores=dict((key, sum([scores1[key] if key in scores1 else 0, scores2[key] if key in scores2 else 0])) for key in set(scores1.keys()+scores2.keys()))
print(finalscores)
# outputs {'a': 30, 'c': 30, 'b': 30, 'd': 10}
This iterates through a set of all keys in both dictionaries, creates a tuple with the values of the key in both dictionaries or 0 and then passes said tuple through the sum function adding the results. Finally, it generates a dictionary.
EDIT
In multiple lines, to understand the logic, this is what the one-liner does:
finalscores = {}
for key in set(scores1.keys()+scores2.keys()):
score_sum = 0
if key in scores1:
score_sum += scores1[key]
if key in scores2:
score_sum += scores2[key]
finalscores[key] = score_sum
For the second solution:
scores1={'a':10,'b':20,'c':30,'d':10} #dictionary holds value scores for a,b,c,d
scores2={'a':20,'b':10} #this dictionary only has scores for keys a and b
for k1 in scores1:
if k1 in scores2:
scores2[k1] += scores1[k1] # Adds scores1[k1] to scores2[k1], equivalent to do scores2[k1] = scores2[k1] + scores1[k1]
else:
scores2[k1] = scores1[k1]
print(scores2)
# outputs {'a': 30, 'c': 30, 'b': 30, 'd': 10}
This question already has answers here:
How do I merge two dictionaries in a single expression in Python?
(43 answers)
Closed 6 years ago.
In python, I have a dictionary named dict_a :
dict_a = {'a':1}
and I want to get a new dictionary dict_b as the update of dict_a,at the same time I don't want to change the dict_a, so I used this:
dict_b = copy.deepcopy(dict_a).update({'b':2})
However, the return value of dict.update is None, so the above code doesn't work. And I have to use this:
temp = copy.deepcopy(dict_a)
temp.update({'b':2})
dict_b = temp
The question is, how to get my goal in one line? Or some
What about:
>>> a = {'a':1}
>>> update = {'b': 1}
>>> b = dict(a.items() + update.items())
>>> b
{'a': 1, 'b': 1}
update - is your value that need to update(extend) dict a
b - is a new resulting dict
Anfd in this case a stay unchanged