Can I concatenate a value when adding to a dictionary in Python? - python

dictionary.setdefault(key, []).append(somelist)
instead of appending lists to the value of a certain key I want to concatenate strings to my value in a loop. So each iteration the key would map to a different value that has been concatenated with a new string. How could I do that?

str values are immutable, so you can't concatenate a string to an existing value; you can only replace the original with a new string formed from the old string. A defaultdict simplifies this.
>>> d = collections.defaultdict(str)
>>> d["foo"] += "bar"
>>> d["foo"] += "baz"
>>> d["foo"]
'barbaz'
setdefault doesn't work here because you can't assign to the return value of setdefault, for example
>>> d.setdefault("foo", "") += "bar"
File "<stdin>", line 1
SyntaxError: can't assign to function call

Set an empty string as a default value, and concatenate as usual
from collections import defaultdict
d = defaultdict(str)
d['a'] += 'hello'
d['a'] += 'world'
print(d)

You can use the dict.get method for a default value of an empty string instead:
dictionary[key] = dictionary.get(key, '') + some_string

Can we get desired output so we have clearer picture of what you mean, from what I read you want to concatenate a string to a dictionary value?
dicta = {'vash': 'the'}
string = ' is concatenating'
lista = [' stampede', string]
for i in lista:
for k in dicta:
dicta[k] += i
print(dicta)
Output:
(xenial)vash#localhost:~/python/stack_overflow$ python3.7 conc.py
{'vash': 'the stampede is concatenating'}

Related

How to store the positions of an element in string in a dictionary (Python)?

I want to get all the positions (indexes) of an element in a string and store them in a dictionary.
This is what I've tried:
string = "This is an example"
test = {letter: pos for pos, letter in enumerate(string)}
But this only gives the last position of the letter. I'd like all positions, desired output:
test["a"]
{8, 13}
At the moment you are overwriting the dictionary values. For example,
>>> my_dict = {}
>>> my_dict['my_val'] = 1 # creating new value
>>> my_dict
{'my_val': 1}
>>> my_dict['my_val'] = 2 # overwriting the value for `my_val`
>>> my_dict
{'my_val': 2}
If you want to keep all values for a key you can use a list along with dict.setdefault method .
>>> print(dict.setdefault.__doc__)
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
>>>
>>> result = {}
>>> string = "This is an example"
>>>
>>> for index, value in enumerate(string):
... result.setdefault(value, []).append(index)
...
>>> result["a"]
[8, 13]
FOR LIST
Creating a dictionary with the keys being the characters in the input_string and the characters being the
indices of the characters in the input_string.
output = {}
Creating a input_string variable called input_string and assigning it the character "This is an example"
input_string = "This is an example"
Iterating through the input_string and assigning the index of the character to index and the character
to character.
output.setdefault(character, []) is checking if the key character exists in the dictionary output. If it does not exist, it will create the key character and assign it the character []. If it does exist, it will return the character of the key character. Then, .append(index) will append the character of index to the character of the key character.
for index, character in enumerate(input_string):
output.setdefault(character, []).append(index)
Desired Output
output["i"]
[2, 5]
In SORT CODE BE LIKE:-
output = {}
input_string = "This is an example"
for index, character in enumerate(input_string):
output.setdefault(character, []).append(index)
FOR DICT/SET
Creating a dictionary with the keys being the characters in the input string and the values being
the indices of the characters in the input string.
output = {}
input_string = "This is an example"
for index, character in enumerate(input_string):
output.setdefault(character, set()).add(index)

Using join() on dictionary in python to return key value pairs as one long string

I want to join() key and value pairs in a my dictionary with a : inbetween. I want to return it all as one string.
Intuitivly I hoped just plugging the dictionary in would work:
def format_grades(grades):
return ': '.join(grades) + "\n"
I tried something like this ': '.join(str(n) for n in grades[n]) to convert my values to strings since my dict looks like this: {john: 2} but I can't think straight now, ideas?
Using f-strings in python3 - you can iterate over the items in the dict and print each on a new line.
print("\n".join(f'{k}: {v}' for k,v in grades.items()))
Example:
grades = {'john': 2, 'marry': 4}
print("\n".join(f'{k}: {v}' for k,v in grades.items()))
Output:
john: 2
marry: 4
def format_grades(grades):
return ( "\n".join([str(i[0])+":"+str(i[1]) for i in grades.items()]) )
You can iterate over the keys and values, and make the string by joining them
grades = {'Joe':'A','John':'B'}
print(" ".join('{}: {}'.format(k,v) for k,v in grades.items()))
#Joe: A John: B

Pythonic way of updating value in dictionary

I have this current code
lst = [1,2,3,4]
c = dict((el,0) for el in lst)
for key in lst:
c[key] += increase_val(key)
Is there a more pythonic way to do it? Like using map? This code words but i would like probably a one-liner or maybe better way of writing this
In my opinion, that is a very clean, readable way of updating the dictionary in the way you wanted.
However, if you are looking for a one-liner, here's one:
new_dict = {x: y + increase_val(x) for x, y in old_dict.items()}
What's different is that this create's a new dictionary instead of updating the original one. If you want to mutate the dictionary in place, I think the plain old for-loop would be the most readable alternative.
In your case no need of c = dict((el,0) for el in lst) statement, because we create dictionary where value of each key is 0.
and in next for loop you are adding increment value to 0 i.e. 0 + 100 = 100, so need of addition also.
You can write code like:
lst = [1,2,3,4]
c = {}
for key in lst:
c[key] = increase_val(key)
collection.Counter()
Use collections.Counter() to remove one iteration over list to create dictionary because default value of every key in your case is 0.
Use Collections library, import collections
Demo:
>>> lst = [1,2,3,4]
>>> data = collections.Counter()
>>> for key in lst:
data[key] += increase_val(key)
collection.defaultdict()
We can use collections.defaultdict also. Just use data = collections.defaultdict(int) in above code. Here default value is zero.
But if we want to set default value to any constant value like 100 then we can use lambda function to set default value to 100
Demo:
>>> data = {}
>>> data["any"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'any'
Get key error because there is on any key in dictionary.
>>> data1 = collections.defaultdict(lambda:0, data)
>>> data1["any"]
0
>>> data1 = collections.defaultdict(lambda:100, data)
>>> data1["any"]
>>> 100

Python Dictionary append value error

I'm trying to append a value (list) to a dictionary unsuccessfully. setting the value by 'equal' works, but appending doesn't.
DurationDict = dict()
DurationDict[str(curYear)] = duration // This works
DurationDict[str(curYear)].append(duration) //This does't work.
any ideas?
If you want to append to the value of dictionary, then value should be a type of list.
lets consider following example:
>>> k = {"a":1}
>>> k["b"] = 2
>>> k["c"] = [2]
>>> k["c"].append("new value") # here you can append because value of c is type of list.
>>> print(k)
{'a': 1, 'c': [2, 'new value'], 'b': 2}
>>> k["b"].append("new value") # here you can not append because value of b is type of int
you can append to a list but not to a dict. python dicts are documented here.
if you want to have a list for all your dictionary entries, you can use defaultdict:
collections import defaultdict
DurationDict = defaultdict(list)
DurationDict[str(curYear)].append(duration)
defaultdict works like a normal dict except it returns the result of the 'factory' - in this case list() if the key you are looking up does not exist yet. you can then append to this (empty) list.
You can only append lists. If you have an empty dictionary d,
d = {} # initialize an empty dictionary
d['a'].append(1) # will NOT work
But if you already had an empty list defined,
d = {'a': []} # initialize with an empty list
df['a'].append(1) # will work
>>> d
{'a': [1]}

Replace dict key by value of other dict

Today I need to replace the key of dict one by value of dict two. Dict one has multiple keys and I only want to replace the keys which match dict 2.
In the end I want to get the dict one back with the old keys (the ones which did not match) and the new keys (which have been changed when they matched)
I wrote the following script but I get no output so I am not sure if I am doing it right, can someone explain to me?
Thanks a lot
ERCC = {}
my_file = open('a.txt')
for line in my_file:
config,name = line.strip().split()
ERCC[contig] = name
RSEM = {}
names_file = open('b.txt')
for line in names_file:
genes, count = line.strip().split()
RSEM[gene] = count
def convert(RSEM,ERCC):
for key, value in RSEM.items():
for keys, values in ERCC.items():
if keys == key:
RSEM[key] = values
return RSEM
print RSEM
convert(RSEM, ERCC)
>>> dic={}
>>> for k,v in myboi.items():
r=input("Enter item to Update write in ""=")
if r:
dic[r]=v
else:
dic[k]=v
Enter item to Update write in ="Mahesh"
Enter item to Update write in ="Saka"
>>>
>>> dic
{'Mahesh': 'Mahesh', 'Saka': 'Mahesh'}
You want compulsary input key in this program you want update one or more time you empty dic={}
result={'Mahesh': 'Mahesh', 'Saka': 'Mahesh'}
>>> fi.close()
>>> fi=open("m.txt","r")
>>> fi.readlines()
['Maheshname']
>>> fi=open("m.txt","w+")
>>> for k,v in myboi.items():
fi.write("'"+k+"'"+":"+"'"+v+"'")
>>> fi.close()
>>> fi=open("m.txt","r")
>>> fi.readlines()
["'Mahesh':'Mahesh''name':'Mahesh'"]
Here's a two-liner for the convert function:
RSEM = {key: ERCC.get(key, RSEM[key]) for key in RSEM}
print RSEM
To dump a dict to a file just do:
with open("your_file_name", "w") as dumpfile:
dumpfile.write(str(RSEM))
Your code seems to be fine. But you have used return statement before print statement. The execution of convert function stops at return *** and the print statement is not executed at all. That is the reason why you are not getting any output.

Categories