Related
I have a dictionary say : my_map_dict which looks something like below:
{2: [['1', '2', '4', '4', '0', '2', '0', '0.67'], ['5', '6', '3', '8', '0', '2', '1', '0.67'], ['6', '9', '4', '9', '0', '2', '2', '0.67'], ['4', '3', '6', '9', '0', '2', '3', '1.00']], 3: [['4', '6', '6', '1', '0', '3', '0', '0.67'], ['5', '9', '4', '8', '0', '3', '1', '0.67']], 4: [['1', '9', '4', '9', '0', '4', '0', '0.67']]}
Where 2,3,4 are the keys of the dictionary and those lists are the values of that.
Now I want to generate a file from this say outputfile.txt which will take all the values of the dictionary and make that a CSV file which looks like below (desired output):
1,2,4,4,0,2,0,0.67
5,6,3,8,0,2,1,0.67
6,9,4,9,0,2,2,0.67
4,3,6,9,0,2,3,1.00
4,6,6,1,0,3,0,0.67
5,9,4,8,0,3,1,0.67
1,9,4,9,0,4,0,0.67
How can I do it?
Flatten the values of your dictionary to a single list of lists, and use the csv module to write to file:
import csv
with open("output.csv","w",newline="") as f:
writer = csv.writer(f)
writer.writerows([item for sublist in d.values() for item in sublist])
output.csv
1,2,4,4,0,2,0,0.67
5,6,3,8,0,2,1,0.67
6,9,4,9,0,2,2,0.67
4,3,6,9,0,2,3,1.00
4,6,6,1,0,3,0,0.67
5,9,4,8,0,3,1,0.67
1,9,4,9,0,4,0,0.67
This question already has answers here:
Joining pairs of elements of a list [duplicate]
(7 answers)
Closed 1 year ago.
['4', '5', '6', '8', '5', '9', '6', '2', '6', '5']
How can I get it to look like this:
[45,68,59,62,65]
How to combine two or more list elements like ['4','5'] to [45]
The strategy is to pair the initial data, then convert to int, zip and slices are a good way dot that
values = ['4', '5', '6', '8', '5', '9', '6', '2', '6', '5']
result = [int(a + b) for a, b in zip(values[::2], values[1::2])]
print(result) # [45, 68, 59, 62, 65]
values[::2] : one over two ['4', '6', '5', '6', '6']
values[1::2] : over over two, starting at 2nd ['5', '8', '9', '2', '5']
I have a list that contains a set of strings like this:
list = ['235,ACCESS,19841136,22564960,4291500,20,527434,566876','046,ALLOWED,24737321,27863065,1086500,3,14208500,14254500']
I'm trying to make the elements of the list a sublist but without splitting the string.
I tried new_list = list(map(list, list)). This is the result taking as reference the first element of the list:
print(new_list[0]):
[['2', '3', '5', ',', 'A', 'C', 'C', 'E', 'S',',','1', '9', '8', '4', '1', '1', '3', '6', ',', '2', '2', '5', '6', '4', '9', '6', '0', ',', '4', '2', '9', '1', '5', '0', '0', ',', '2', '0', ',', '5', '2', '7', '4', '3', '4', ',', '5', '6', '6', '8', '7', '6']]
I would like this output:
print(new_list[0]):
[[235,'ACCESS',19841136,22564960,4291500,20,527434,566876]]
Thanks in advance for your help!
You can try split() with delimiter , like this -
new_list = [i.split(',') for i in list]
print (new_list[0])
Output:
['235', 'ACCESS', '19841136', '22564960', '4291500', '20', '527434', '566876']
One thing is that here the numbers are also represented as string. If you want integers instead you can use isdigit() method like this -
new_list = [[int(e) if e.isdigit() else e for e in i.split(',') ]for i in list]
print(new_list[0])
Output:
[235, 'ACCESS', 19841136, 22564960, 4291500, 20, 527434, 566876]
Also, please try to avoid naming your list list
First off i am certain that such a basic thing has been asked before, but i could not find a post about it.
I have this piece of example data:
'192.168.244.213': ['8', '4', '3', '1', '6', '5', '3', '2', '6', '5'],
'192.168.244.214': ['6', '8', '7', '6', '5', '4', '2', '7', '5', '5'],
'192.168.244.215': ['4', '10', '0', '8', '7', '0', '4', '3', '2', '6'],
'192.168.244.230': ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
And i want to print out every line (each line is one dictionary key-value pair) that has a list-value whose list contains any amount of items that is not 0 (in this case, every line except the 4th)
I just cant seem to figure out this seemingly simple thing - what i tried before was those two things:
for i in d.keys():
if "0" not in d[i]:
print(i, d[i])
This one shows only lists that do not contain 0 AT ALL - so the third line would not be shown, even though it contains non-0 values
for i in d.keys():
for j in d[i]:
if j is not "0":
print(i, d[i])
This one DOES show me what i want, but as you can tell, it prints every result way too often - one print for every list value that is not 0.
You can simply iterate over like
def all_zero(arr):
for i in arr:
if i != 0:
return False
else:
return True
You can call it on all the lists one by one.
Use a dictionary-comprehension:
d = {'192.168.244.213': ['8', '4', '3', '1', '6', '5', '3', '2', '6', '5'],
'192.168.244.214': ['6', '8', '7', '6', '5', '4', '2', '7', '5', '5'],
'192.168.244.215': ['4', '10', '0', '8', '7', '0', '4', '3', '2', '6'],
'192.168.244.230': ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0']}
result = {k: v for k, v in d.items() if not all(x == '0' for x in v)}
# {'192.168.244.213': ['8', '4', '3', '1', '6', '5', '3', '2', '6', '5'],
# '192.168.244.214': ['6', '8', '7', '6', '5', '4', '2', '7', '5', '5'],
# '192.168.244.215': ['4', '10', '0', '8', '7', '0', '4', '3', '2', '6']}
The above code generates a new dictionary which omits all items where values are all zeros.
Now that you have a dictionary, you can easily do an iteration like so:
for k, v in result.items():
print(k, v)
Your bug is basically just a missing break:
for i in d.keys():
for j in d[i]:
if j != "0":
print(i, d[i])
break
However, for conciseness I would recommend you check out the any() function, which does exactly what you want: Return true if any of the elements of the iterable are true (when cast to booleans).
Eg:
for i in d.keys():
if any(j != "0" for j in d[i]):
print(i, d[i])
(The j is not "0" generator is only necessary because you have string values. For an int array, any(d[i]) would work.)
Even more "Pythonic" would be removing the need for a dictionary lookup:
for i, d_i in d.items():
if any(j != "0" for j in d_i):
print(i, d_i)
I like the other answers but I feel like you can get away with something like this as well:
for i in d.keys():
#If there are as many zeroes as there are elements in the list...
if d[i].count(0) == len(d[i]):
#...You might as well skip it :)
continue
print(d[i])
for i in d.keys():
all_zero = True
for j in d[i]:
if j is not "0":
all_zero = False
break
if not all_zero:
print(i, d[i])
This may work for almost every language :)
Have a look at how I could accomplish this.
d = {
'192.168.244.213': ['8', '4', '3', '1', '6', '5', '3', '2', '6', '5'],
'192.168.244.214': ['6', '8', '7', '6', '5', '4', '2', '7', '5', '5'],
'192.168.244.215': ['4', '10', '0', '8', '7', '0', '4', '3', '2', '6'],
'192.168.244.230': ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
}
for key in d.keys():
if all( item == '0' for item in d[key]):
pass
else:
print(key, d[key])
You should use all in this case, consider following example:
digits = ['0', '2', '0', '4', '7', '5', '0', '3', '2', '6']
zeros = ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
print(all([k=='0' for k in digits])) #gives False
print(all([k=='0' for k in zeros])) #gives True
Please remember to deliver [k=='0' for k in ...] to all, as delivering list directly would give True for both digits and zeros, as both contain at least one non-empty str (str of length 1 or greater).
I want my code to cycle through each item of the list and convert it from str to int but it only converts half of the list and in an irregular order.
My code:
for item in list:
list.append(int(item))
list.remove(item)
print (list)
For example if list is ['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
The final would be ['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
Which is only half converted and not in order.
I could do it another way but that is a lot longer so would like to fix this and add to my knowledge about for loops.
My knowledge and experience with Python is tiny, so I most probably won't understand unless it's really basic and jargon is explained.
Using list comprehension:
l = ['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
output = [int(i) for i in l]
print(output)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]
If you don't understand list comprehension you could use simple for loop:
l1 = []
for i in l:
l1.append(int(i))
print(l1)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]
Both answers above are good but why your code didn't work also should be adressed.
First , you are changing the list while you are iterating on it. This is something you should not do. It will probably cause problems, like in your question.
Second, remove method removes the first element in the list that it encounters which fits the given argument, it also should be used with care.
Third, you should not use list as an variable name. As it is a built-in class.
for item in list:
print (list)
list.append(int(item))
list.remove(item)
# Prints
['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
['6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8', 5]
['6', '5', '6', '2', '6', '8', '5', '4', '2', '8', 5, 3]
['5', '6', '2', '6', '8', '5', '4', '2', '8', 5, 3, 6]
['5', '2', '6', '8', '5', '4', '2', '8', 5, 3, 6, 6]
['2', '6', '8', '5', '4', '2', '8', 5, 3, 6, 6, 5]
['6', '8', '5', '4', '2', '8', 5, 3, 6, 6, 5, 2]
['6', '8', '5', '4', '2', '8', 3, 6, 6, 5, 2, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 5, 2, 5, 6]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 5, 6, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
As you see, not working as expected
Why don't you use something like this:
l = list(map(int, l))
It simply calls function int on each item from l.
Here's doc.
While the other two answers give you better ways of converting your list of strings to integers, they really don't answer your question. Your main problem is that you are mutating (altering) the list structure while your for loop operates on it. You should not mutate the list structure (remove elements or append) because the loop iteration variable item gets out of sync. There's no way to re-sync item to the new list structure.
BTW: It's not a random order. It's every other item.
You could write your conversion loop like so, because you're not mutating the structure of the list, only the individual elements:
for i in xrange(len(l)):
l[i] = int(l[i])
Don't write it like this:
for item in l:
item = int(item)
It doesn't mutate the individual list elements, even though you would think that it does. It has to do with how Python iterators work.
Try this:
>>> list = ['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
>>> for item in list[:]:
... list.append(int(item))
... list.remove(item)
...
>>> print(list)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]
Explanation: Here we are iterating over a clone of the list but doing operations on the original list.
PS: list is a keyword in python. Its usage as a variable name should be avoided.