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
Related
As I was studying Python, I came across this task:
Imagine Python did not have built-in support for sets. Show how we
could use dictionaries to represent sets. Write the four set
operations | - ^ & for this new representation of sets.
Below you can see the answer:
First, for the ‘or’ operation, we add entries to the new dictionary
from both input lists:
l1 = [1,2,3,4,5]
l2 = [4,5,6,7,8]
def t_or(l1,l2):
result = {}
for x in l1: result[x] = 0
for x in l2: result[x] = 0
print(result)
So, I'm wondering why have the author used such a strange method to add entries result[x] = 0? Isn't there a better way to do it, maybe using alternatives methods like .add, .insert, etc?
result[key] = value is the way to assign a new pair key:value in a Python dictionary. You don't have to create the entry key first on a Dictionary. If you come from Java, for example, the syntaxis is like:
Map<String, String> result = new HashMap<int, int>();
result.put(1, 0);
As you can see, on Java you are not declaring the key too, the same happens on a lot of languages and that is because of how a dictionary key works.
When you want to retrieve an element from a dictionary, you have to be sure that the key already exists in the dictionary, otherwise it will throw an exception.
The .add or .insert that you have in mind in Python is .append and it is used to add a new element to a list:
my_list = []
my_list.append(0)
So no, there is no a better way or a different way to assign new key:value pairs on a Python dictionary.
I am trying to remove a position from an empty list, as a simple example that demonstrates or is trying to remove.
#Test about fruits
fruits = []
fruits.append('maça')
fruits.append('goiaba')
fruits.append('uva')
fruits.append('pera')
fruits.append('bananna')
fruits[1] = []
print (fruits)
Output : ['maça', [], 'uva', 'pera', 'bananna']
Desired output ['maça', 'uva', 'pera', 'bananna']
Just remembering that it is a simple example, so I can apply it in a more robust program that I am developing that presents the same problem of having a "position" in the list with a 'null' or empty value in this case.
Use pop() to remove an element from a list by its index, rather than assigning an empty value to the index.
fruits.pop(1)
or del
del fruits[1]
pop() allows you to retrieve the value being removed at the same time.
You can use
del fruits[1]
See Difference between del, remove and pop on lists for the differences.
I'm trying to write something that answers "what are the possible values in every column?"
I created a dictionary called all_col_vals and iterate from 1 to however many columns my dataframe has. However, when reading about this online, someone stated this looked too much like Java and the more pythonic way would be to use zip. I can't see how I could use zip here.
all_col_vals = {}
for index in range(RCSRdf.shape[1]):
all_col_vals[RCSRdf.iloc[:,index].name] = set(RCSRdf.iloc[:,index])
The output looks like 'CFN Network': {nan, 'N521', 'N536', 'N401', 'N612', 'N204'}, 'Exam': {'EXRC', 'MXRN', 'HXRT', 'MXRC'} and shows all the possible values for that specific column. The key is the column name.
I think #piRSquared's comment is the best option, so I'm going to steal it as an answer and add some explanation.
Answer
Assuming you don't have duplicate columns, use the following:
{k : {*df[k]} for k in df}
Explanation
k represents a column name in df. You don't have to use the .columns attribute to access them because a pandas.DataFrame works similarly to a python dict
df[k] represents the series k
{*df[k]} unpacks the values from the series and places them in a set ({}) which only keeps distinct elements by definition (see definition of a set).
Lastly, using list comprehension to create the dict is faster than defining an empty dict and adding new keys to it via a for-loop.
I am new to Python. while initializing a list
mylist = list()
mylist[0]="hello"
gives error .It only works
mylist.append("hello")
but if i do same with dictionary
mydict ={}
mydict["one"]="hello"
it works.
why i dont need to do
mydict['one'].append('hello')
why things are different for different structures.
If you update a dict like this:
d['c'] = 3
... there is no need for d['a'] and d['b'] (or any item at all, for that matter) to be present in that dict. The key of a dictionary item does not imply any specific structural properties of your dict object.
However, if you want to update a list like this:
l[5] = 'a'
... the indexes 0 through 5 absolutely must exist. The index not only serves as a handle for an element in the list, but also has structural properties. If l[5] does exist, you can be absolutely sure that indexes 0 through 4 do as well. And you need that certainty.
Imagine you could do l[5] = 'a' on an empty list. What would len(l) return? 1? 6?
Both cases would cause this to fail:
for i in range(len(l)):
print(l[i])
One can argue that l[<index>] = 'a' could implicitly append that value if index-1 already exists or if the list is empty and the desired index is 0. In order for this to reliably work, you would need to ensure that index-1 exists before adding values like this, while, when using append(), you are guaranteed that your value will be added to the list (except for potential edge cases like memory starvation).
If you add an element to a dictionary you connect to a key.
In your case you connect the element 'hello' to your key 'one'
To add an element to a list you will have to use the function list.append.
You use list[x] to get the element at position x.
I am currently writing a small bit of logic for my HTML page. My aim is to create variables (lists) within an iteration (using the iteration to create the names of said lists as the amount of them will be unknown to the program). I am currently creating the lists like this:
maps={}
currentMap = elements[0].process
counter=0
for i in elements:
if(counter==0):
maps["mapsEle{0}".format(counter)]=[]
counter+=1
if(i.process!=currentMap):
currentMap = i.process
maps["mapEle{0}".format(counter)]=[]
counter+=1
else:
print("No change found, keeping heading the same.")
However as you can probably tell, this does not create a list but a string. I try to print the variables (e.g. mapsEle0) and it returns the variable name (e.g. print(mapsEle0) returns "mapsEle0") this too me is suprising as I would have thought if the dictionary is saving it as a string it would print "[]".
So I am looking for a way to create lists within the dictionary in that iteration I am using there, basically want to just reformat my declaration. Cheers in advance everyone :)
Edit:
As requested here is the code where I attempt to append. Please note I want to append 'i' into the lists and no the dictionary.
for i in maps:
for x in elements:
if(x.process!=currentMap):
currentMap=x.process
elif(x.process==currentMap):
#i.append(x)
The syntax of your print statement is wrong, if you want to access the contents of the dictionary, you need to use different notation.
Instead of print('mapsEle0') you need to do print(maps['mapsEle0']).
Update:
Unfortunately your description of what you want and your code are a bit conflicting, so if you can, please try to explain some more what this code is supposed to do.
for i in maps.iterkeys():
for x in elements:
if(x.process!=currentMap):
currentMap=x.process
elif(x.process==currentMap):
maps[i].append(x)
This will iterate over all keys of maps ('mapsEle0'...'mapsEleN') and add x to the contained list if the elif condition is fulfilled.
You're printing the string by doing print('mapsEle0').
To print the dict, you must print(maps) - 'll print the whole dictionary, OR, to print a specific key/element print(maps['mapsEle0'])
To elaborate it further here's a interpreter session:
>>> maps = {}
>>> counter = 0
>>> maps["mapsEle{0}".format(counter)]=[]
>>> maps
{'mapsEle0': []}
>>>
>>> print(maps)
{'mapsEle0': []}
>>>
>>> print(maps['mapsEle0'])
[]
>>>
For the append part:
>>> maps['mapsEle1'].append('hello')
>>> print(maps['mapsEle1'])
['hello']
Edit 2: Your statement is still not clear
As requested here is the code where I attempt to append. Please note I
want to append 'i' into the lists and no the dictionary.
I think sobek has got it right - you want to append x to the mapsEle0, mapsEle1 lists, which are keys in maps dictionary.
for i in maps.iterkeys():
for x in elements:
if(x.process!=currentMap):
currentMap=x.process
elif(x.process==currentMap):
maps[i].append(x)