reading a csv file into a Networkx graph in python 3.5 - python-3.x

I am following this tutorial: graph tutorial on my own data file. but I am getting stuck on the last bit. the code seems to throw:
(most recent call last)<ipython-input-193-7227d35394c0> in <module>()
1 for node in links: #loops through each link and changes each dictionary to a tuple so networkx can read in the information
2 edges = node.items()
----> 3 G.add_edge(*edges[0]) #takes the tuple from the list and unpacks the tuples
4
5 nx.draw(G)
TypeError: 'dict_items' object does not support indexing
is there a fix? I'm sort of stuck.

This is probably python-2 only compatible code.
In python 2, dict.items() returns a list of tuples (key, value) as opposed to dict.iteritems()
In python 3, dict.iteritems() has been removed, and dict.items() returns an iterator.
So you have to explicitly convert it to list to get access to the elements by index:
edges = list(node.items())

Related

Getting TypeError: list indices must be integers when using list[:,colIndex] to get column data as list

I have a 2D list (a list of lists) and am trying to use the notation list[:,colIndex] to pull out a single column's data into another list, but I'm getting a TypeError: list indices must be integers error.
for example:
lst = [[1,2,3],[10,12,13]]
lst[:,0]
Returns:
Traceback (most recent call last):
File "<input>", line 2, in <module>
TypeError: list indices must be integers
I don't understand...
Edit:
Running this in Python 3.9 gives me:
TypeError: list indices must be integers or slices, not tuple
It would seem that the [:,colIndex] syntax isn't supported by lists and is available to numpy arrays only :(
However I can use: list(zip(*lst))[colIndex] instead from this answer https://stackoverflow.com/a/44360278/1733467

How do I nest a For Loop w/ IF statement to return a new list?

Can the return in an If statement append a list?
Is python aware that the list elements are actually dictionaries and that 'sublist' iterates over those elements?
I tried being data type specific after For previously and that doesn't help
Is the If statement actually accessing the dictionary?
My code:
In[1]: restaurants = [fork_fig, frontier_restaurant]
In [2]: def open_restaurants(restaurants):
for sublsit in restaurants:
op=[]
if sublist.get('is_closed')==False:
op.append(sublist.get('name'))
passed through their code:
In [1]: len(open_restaurants(restaurants))
Out[2]: NameErrorTraceback (most recent call last)
<ipython-input-14-e78afc732a29> in <module>
----> 1 len(open_restaurants(restaurants)) # 1
<ipython-input-13-56ad484d6dd9> in open_restaurants(restaurants)
2 for sublsit in restaurants:
3 op=[]
----> 4 if sublist.get('is_closed')==False:
5 op.append(sublist.get('name'))
6
NameError: name 'sublist' is not defined
and next: I think this is because the list i defined is not populating with the correct information.
In[3]: open_restaurants(restaurants)[0]['name'] # 'Fork & Fig'
Out[4]:TypeErrorTraceback (most recent call last)
<ipython-input-15-bf5607d088f4> in <module>
----> 1 open_restaurants(restaurants)[0]['name'] # 'Fork & Fig'
TypeError: 'NoneType' object is not subscriptable
Your indentation may be not correct
You didn't return the result (probably return op) in your function
The problem here was that I was entering too much information.
The code that ended up working perfectly was as follows:
def open_restaurants(restaurants):
op=[]
for sublist in restaurants:
if sublist['is_closed']==False:
op.append(sublist)
return op
I separated op list from the for loop.
Previously, the NameError said sublist was not defined, yet it was
defined by including it in the For; to fix I removed .get() and
replaced it with list form x[].
Last, separated return from the .append() function.

How can I make my dictionary be able to be indexed by a function in python 3.x

I am trying to make a program that finds out how many integers in a list are not the integer that is represented the most in that list. To do that I have a command which creates a dictionary with every value in the list and the number of times it is represented in it. Next I try to create a new list with all items from the older list except the most represented value so I can count the length of the list. The problem is that I cannot access the most represented value in the dictionary as I get an error code.
import operator
import collections
a = [7, 155, 12, 155]
dictionary = collections.Counter(a).items()
b = []
for i in a:
if a != dictionary[max(iter(dictionary), key=operator.itemgetter(1))[0]]:
b.append(a)
I get this error code: TypeError: 'dict_items' object does not support indexing
The variable you called dictionary is not a dict but a dict_items.
>>> type(dictionary)
<class 'dict_items'>
>>> help(dict.items)
items(...)
D.items() -> a set-like object providing a view on D's items
and sets are iterable, not indexable:
for di in dictionary: print(di) # is ok
dictionary[0] # triggers the error you saw
Note that Counter is very rich, maybe using Counter.most_common would do the trick.

python 3 numpy save multiple arrays

I have 3 arrays and one list:
array1.shape = (1000,5,5,7)
array2.shape = (1000,)
array3.shape = (1000,)
len(list1) = (1000)
I want to save all of these to a numpy file. When I used to run in Python 2.7, the command I used to use was:
np.save(filename,[array1, array2, array3, list1])
And everything worked great, including loading all of the data with np.load. However, when I try this command in Python 3.6 I get an error:
could not broadcast input array from shape (1000,5,5,7) into shape (1000)
How am I able to save the 3 arrays as well as the list into a single numpy array in Python 3.6?

using Python 3.7, how to use of numpy complex with an array of values

I am new to Python, so I apologize ahead of time if this question is too basic.
Say I have a complex value 50+ j(10 w), where w is an array of frequencies, for example,
import numpy as np
w=2*np.pi*np.linspace(1800e6,2400e6,100)
how do I use np.complex to calculate the complex value for each value in the w array (or any other way to accomplish this)?
In Matlab, I could do
z = 50 + i.*w.*10
(although I don't think I would need to since everything else is a scalar in the equation, but this helps show what I want to do --element by element multiplication).
Anyway, when I try:
z=np.complex(50,10*w)
I get the following error:
Traceback (most recent call last):
File "<ipython-input-14-a78f7e2cf118>", line 1, in <module>
z=np.complex(50,10*w)
TypeError: only size-1 arrays can be converted to Python scalars'
I appreciate any help. Thank you.

Resources