Creating multiple lists within a dictionary using an iteration - python

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)

Related

Using range function in Python

I am new to learning Python and have a question about using the range function to iterate a string.
Let's say I need to capitalize everything in the following string:
string = 'a b c d e f g'
Can I just write the following code?
for i in string:
i = i.upper()
return string
Or should I use the range function to iterate every element in the string?
Finally, a more general question is whenever I need to iterate all elements in a string/list, when should I use the range function and when can I just use the "for" loop?
Strings are a bad example, because strings in Python cannot be changed. You have to build a new one:
new = ''
for i in string:
new += i.upper()
For the sake of example, we're all going to ignore the fact that new = string.upper() would do this in one statement.
In general, when you iterate through an object, you are handed references to the members. You can't change the container object, but if the inner object is mutable, you can change it. Consider this silly example:
a = [[1],[2],[3],[4]]
for element in a:
element[0] *= 2
This will result in a being [[2],[4],[6],[8]], because we are allowed to modify those inner lists. We can't change the outer list.
AS A GENERAL RULE, if you find yourself writing for i in range(len(xxx)):, then there is a better way to do it. It isn't ALWAYS true, but it's a key Python learning point.

Python: How can I use an enumerate element as a string?

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

Python : initializing list and dictionary

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.

how this for loop is used in python

Please let me know how this for loop is working.
points = {0,1,2,3,4,8,1}
x = float(sum([len(points) for i in points]))
print(x)
This code snippet is giving me output as:-
36.0
List comprehensions are not that hard if you take a look at a very simple example:
[T(x) for x in X]
The first term is declaring what should be done with all the individual items in the collection we are iterating over. This might be type conversion or just extracting a specific value from a dict.
The symbol after the for just defines the name for our iteration variable and the last term is the collection(list, set, dict etc.) which we iterate through.
A more verbose implementation of the same thing could be:
result = []
for i in range(len(X)):
result.append(T(X[i]))
After this the content of result is the same as the list returned by the list comprehension.

Python: removing specific lines from an object

I have a bit of a weird question here.
I am using iperf to test performance between a device and a server. I get the results of this test over SSH, which I then want to parse into values using a parser that has already been made. However, there are several lines at the top of the results (which I read into an object of lines) that I don't want to go into the parser. I know exactly how many lines I need to remove from the top each time though. Is there any way to drop specific entries out of a list? Something like this in psuedo-python
print list
["line1","line2","line3","line4"]
list = list.drop([0 - 1])
print list
["line3","line4"]
If anyone knows anything I could use I would really appreciate you helping me out. The only thing I can think of is writing a loop to iterate through and make a new list only putting in what I need. Anyway, thanlks!
Michael
Slices:
l = ["line1","line2","line3","line4"]
print l[2:] # print from 2nd element (including) onwards
["line3","line4"]
Slices syntax is [from(included):to(excluded):step]. Each part is optional. So you can write [:] to get the whole list (or any iterable for that matter -- string and tuple as an example from the built-ins). You can also use negative indexes, so [:-2] means from beginning to the second last element. You can also step backwards, [::-1] means get all, but in reversed order.
Also, don't use list as a variable name. It overrides the built-in list class.
This is what the slice operator is for:
>>> before = [1,2,3,4]
>>> after = before[2:]
>>> print after
[3, 4]
In this instance, before[2:] says 'give me the elements of the list before, starting at element 2 and all the way until the end.'
(also -- don't use reserved words like list or dict as variable names -- doing that can lead to confusing bugs)
You can use slices for that:
>>> l = ["line1","line2","line3","line4"] # don't use "list" as variable name, it's a built-in.
>>> print l[2:] # to discard items up to some point, specify a starting index and no stop point.
['line3', 'line4']
>>> print l[:1] + l[3:] # to drop items "in the middle", join two slices.
['line1', 'line4']
why not use a basic list slice? something like:
list = list[3:] #everything from the 3 position to the end
You want del for that
del list[:2]
You can use "del" statment to remove specific entries :
del(list[0]) # remove entry 0
del(list[0:2]) # remove entries 0 and 1

Categories