New to python, trying to figure out how to replace words using a dict.
It is setup like:
list = {"word1":"word2",
"word3":"word4",
"word5":"word6"
}
I have :
for w in list:
new_list = old_list.replace(w)
Thanks!
As pointed out in the comment, list is a built-in name, and you have overwritten it - this might cause weird behaviour.
Your syntax for creating the dictionary is correct, but let's call it my_dict.
Now what are you trying to do? Your title suggets, that you want to replace substrings and not elements in lists?
Anyway, the for-loop loops over the keys of the dictionary. So inside it you should do my_string.replace(my_dict, my_dict[w])
Alternatively, you can loop over the key-value-pairs: for k, v in my_dict.items(). Inside this loop you can use my_string.replace(k, v)
Related
I have a list of dict1.keys() I'm enumerating over and I'd like to use the element as a string.
for i,j in enumerate(dict1.keys()): str(j) = somethingElse
>>> SyntaxError: can't assign to function call
https://dbader.org/blog/python-enumerate describes the enumerate entities as a tuple of: (index, element). The type(j) is <class 'str'>, which I can print, but not use as a variable.
EDIT:
for i,j in enumerate(dict1.keys()): j = somethingElse
EDIT2:
I think the problem may be with pandas. The first line works, not the second.
for i,j in enumerate(dict1.keys()): list1.append(j)
for i,k in enumerate(list1): k = pd.DataFrame(dict1[k]['Values'])
EDIT3:
That second line does work, but only for only ends up with one df, with name 'k' instead of the key. But heres what Im trying to. Each dict converted to a df using its key name:
for i,j in enumerate(dict1.keys()): j = pd.DataFrame(dict1[j]['Values'])
EDIT4:
According to the comments below, I switched to a for loop on the keys (which dont need to be explicitly called), but it still won't use the element 'i' as a variable. However, from the question linked below, elements are able to be used as a key in a dict. After reducing the question to "use list item as name for dataframe" and searching that, it verks. I'll post as an answer also:
dict2={}
for i in dict1: dict2[i] = pd.DataFrame(dict1[i]['Values'])
..thus the names are preserved. Actually, this is similar to Sheri's answer with lists, but the names retain association with the dfs. There may not be a way to set a variable value using something other than a plain string, but I'll start a different question for that.
use elements in a list for dataframe names
Because you are generating your pandas dataframe dynamically inside a for loop so at the end when you print j it will show you the last generated dataframe. You should store your dataframe in list Try using this:
listOfFrame = []
for j in dict.keys():
j = pd.DataFrame(dict[j]['Values'])
listOfFrame.append(j)
Indeed j will be a str (or whatever else type of key you are using in dict).
The actual problem is with the loop body, as the error message states:
str(j) = somethingElse
is not valid Python. The left hand side is a call to the str function, so you cannot assign a value to it.
Based on the comments you want neither enumerate nor to iterate over the dict keys. Instead, you want to iterate over its values:
dfs = []
for val in dict1.values():
dfs.append(pd.DataFrame(val['Values']))
However, this would normally written without an explicit loop in Python, for instance by using list comprehension:
dfs = [pd.DataFrame(val['Values']) for val in dict1.values()]
From the question linked below, elements are able to be used as a key in a dict. After reducing the question to "use list item as name for dataframe" and searching that, it verks. I'll post as an answer also:
dict2={}
for i in dict1: dict2[i] = pd.DataFrame(dict1[i]['Values'])
..thus the names are preserved. Actually, this is similar to Sheri's answer with lists, but the names retain association with the dfs. There may not be a way to set a variable value using something other than a plain string, but I'll start a different question for that.
use elements in a list for dataframe names
I have defined a function called modify which modifies given string. I have a dict called elements which have some strings stored in them. However, I am unable to modify those strings stored in the dict.
x = "abc"
x = modify(x)
This works but when I do;
for element in elements:
element = modify(element)
This does not work. Any idea why? I'm fairly new to python.
You cannot modify the elements of a dict whilst iterating through them.
You'd need to use something like this:
for key in elements:
elements[key] = modify(elements[key])
If you need to apply a function to each member of a dictionary, consider using a dict comprehension:
elements = {k: modify(v) for k, v in elements.items()}
If you are using python 2.7 use elements.iteritems() instead of elements.items().
I need to concatenate a list of key value pairs with comma in between each item. Meaning that if I have a dictionary like this:
{A:0,B:0,C:1}
I need to have an output like:
A0,B0,C1
without spaces.
I have written this piece of code, but it is only printing the keys of the dictionaries. It is not printing the values.
weights = {'A':0, 'B':0, 'C':1}
for each in weights:
weights[each]= 1
logs = ",".join(weights)
Output I'm getting:
A,B,C
Output expected:
A1,B1,C1
I've have tried to put weights.keys() and .values(), but then I don't know how to put those together.
Thank you very much for the help.
This is the way Python dictionaries behave when iterated over. To get the behaviour you want do:
logs = ",".join(key + str(value) for key, value in weights.items())
Also, if only need it for debugging you can just print the result of weights.items().
To relate it to your code:
d = {'A':0,'B':0,'C':1}
s = []
for k, v in d.items():
s.append("{}{}".format(k,v))
print(','.join(s))
Then, you can ultimately shorten that to one line:
Pay attention to the fact there are no square brackets here. We are actually using a generator expression here, which is more efficient than making a list comprehension in this case.
print(",".join("{}{}".format(k,v) for k, v in d.items()))
Dictionaries usually iterate by keys. And the order is arbitrary. For the output you're seeking, you may prefer to sort and iterate the item pairs like this:
>>> ','.join('{}{}'.format(k,v) for k,v in sorted(weights.items()))
'A0,B0,C1'
Dictionaries are key,value pairs. For the expected output you need to have both :
','.join('{}{}'.format(k,v) for k,v in sorted(weights.items()))
You can use weights.items() to get the key-value pair, and then join them. Then, join those joins with a comma. It can all be done with a list comprehension:
>>> ",".join("{}{}".format(*items) for items in weights.items())
A0,B0,C1
This way, you could change your mind later and decide to put a colon in there, for example:
>>> ",".join("{}:{}".format(*items) for items in weights.items())
A:0,B:0,C:1
I have a dictionary where each value is a list, like so:
dictA = {1:['a','b','c'],2:['d','e']}
Unfortunately, I cannot change this structure to get around my problem
I want to gather all of the entries of the lists into one single list, as follows:
['a','b','c','d','e']
Additionally, I want to do this only once within an if-block. Since I only want to do it once, I do not want to store it to an intermediate variable, so naturally, a list comprehension is the way to go. But how? My first guess,
[dictA[key] for key in dictA.keys()]
yields,
[['a','b','c'],['d','e']]
which does not work because
'a' in [['a','b','c'],['d','e']]
yields False. Everything else I've tried has used some sort of illegal syntax.
How might I perform such a comprehension?
Loop over the returned list too (looping directly over a dictionary gives you keys as well):
[value for key in dictA for value in dictA[key]]
or more directly using dictA.itervalues():
[value for lst in dictA.itervalues() for value in lst]
List comprehensions let you nest loops; read the above loops as if they are nested in the same order:
for lst in dictA.itervalues():
for value in lst:
# append value to the output list
Or use itertools.chain.from_iterable():
from itertools import chain
list(chain.from_iterable(dictA.itervalues()))
The latter takes a sequence of sequences and lets you loop over them as if they were one big list. dictA.itervalues() gives you a sequence of lists, and chain() puts them together for list() to iterate over and build one big list out of them.
If all you are doing is testing for membership among all the values, then what you really want is to a simple way to loop over all the values, and testing your value against each until you find a match. The any() function together with a suitable generator expression does just that:
any('a' in lst for lst in dictA.itervalues())
This will return True as soon as any value in dictA has 'a' listed, and stop looping over .itervalues() early.
If you're actually checking for membership (your a in... example), you could rewrite it as:
if any('a' in val for val in dictA.itervalues()):
# do something
This saves having to flatten the list if that's not actually required.
In this particular case, you can just use a nested comprehension:
[value for key in dictA.keys() for value in dictA[key]]
But in general, if you've already figured out how to turn something into a nested list, you can flatten any nested iterable with chain.from_iterable:
itertools.chain.from_iterable(dictA[key] for key in dictA.keys())
This returns an iterator, not a list; if you need a list, just do it explicitly:
list(itertools.chain.from_iterable(dictA[key] for key in dictA.keys()))
As a side note, for key in dictA.keys() does the same thing as for key in dictA, except that in older versions of Python, it will waste time and memory making an extra list of the keys. As the documentation says, iter on a dict is the same as iterkeys.
So, in all of the versions above, it's better to just use in dictA instead.
In simple code just for understanding this might be helpful
ListA=[]
dictA = {1:['a','b','c'],2:['d','e']}
for keys in dictA:
for values in dictA[keys]:
ListA.append(values)
You can do some like ..
output_list = []
[ output_list.extend(x) for x in {1:['a','b','c'],2:['d','e']}.values()]
output_list will be ['a', 'b', 'c', 'd', 'e']
I'm playing with some loops in python. I am quite familiar with using the "for" loop:
for x in y:
do something
You can also create a simple list using a loop:
i = []
for x in y:
i.append(x)
and then I recently discovered a nice efficient type of loop, here on Stack, to build a list (is there a name for this type of loop? I'd really like to know so I can search on it a little better):
[x.name for x in y]
Ok, that being said, I wanted to go further with the last type of loop and I tried to build a python dictionary using the same type of logic:
{x[row.SITE_NAME] = row.LOOKUP_TABLE for row in cursor}
instead of using:
x = {}
for row in cursor:
x[row.SITE_NAME] = row.LOOKUP_TABLE
I get an error message on the equal sign telling me it's an invalid syntax. I believe in this case, it's basically telling me that equal sign is a conditional clause (==), not a declaration of a variable.
My second question is, can I build a python dictionary using this type of loop or am I way off base? If so, how would I structure it?
The short form is as follows (called dict comprehension, as analogy to the list comprehension, set comprehension etc.):
x = { row.SITE_NAME : row.LOOKUP_TABLE for row in cursor }
so in general given some _container with some kind of elements and a function _value which for a given element returns the value that you want to add to this key in the dictionary:
{ _key : _value(_key) for _key in _container }
What you're using is called a list comprehension. They're pretty awesome ;)
They have a cousin called a generator expression that works like a list comprehension but instead of building the list all at once, they generate one item at a time. Hence the name generator. You can even build functions that are generators - there are plenty of questions and sites to cover that info, though.
You can do one of two things:
x = dict(((row.SITE_NAME, row.LOOKUP_TABLE) for row in cursor))
Or, if you have a sufficiently new version of Python, there is something called a dictionary comprehension - which works like a list comprehension, but produces a dictionary instead.
x = {row.SITE_NAME : row.LOOKUP_TABLE for row in cursor}
You can do it like this:
x = dict((row.SITE_NAME, row.LOOKUP_TABLE) for row in cursor)