Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a list of pairs of words, and am trying to prepare them as data for NetworkX to read. Part of the script is iterating over the pairs to map them to id numbers (see code below). This code throws an Index out of range-error that I need to get past. What is the mistake here?
coocs = [['parttim;work'], ['parttim;work'],['parttim;visit'], ['parttim;site'], ['parttim;uncl'], ['parttim;home'], ['parttim;onlin']]
unique_coocs = list(set([row[0] for row in coocs])) # remove redundance
ids = list(enumerate(unique_coocs)) # creates a list of tuples with unique ids and their names for each word in the network
keys = {name: i for i, name in enumerate(unique_coocs)} # creates a dictionary(hash map) that maps each id to the words
links = [] # creates a blank list
for row in coocs: # maps all of the names in the list to their id number
try:
links.append({keys[row[0]]: keys[row[1]]})
except:
links.append({row[0]: row[1]})
Mistake occurs at row, because len(row) in always 1 here, So you cannot use the index number 1 which is row[1]
Corrected code is,
for row in coocs:
links.append(row[0]+':'+str(keys[row[0]]))
print links
Output:
['parttim;work:2', 'parttim;work:2', 'parttim;visit:3', 'parttim;site:4', 'parttim;uncl:0', 'parttim;home:5', 'parttim;onlin:1']
This works fine
for row in coocs: # maps all of the names in the list to their id number
links.append({row[0]: keys[row[0]]})
>>> links
[{'parttim;work': 2}, {'parttim;work': 2}, {'parttim;visit': 3}, {'parttim;site': 4}, {'parttim;uncl': 0}, {'parttim;home': 5}, {'parttim;onlin': 1}]
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to create and use a dynamic variable in Python for the first time.
for i in range(0,len(test_data)):
globals()["test_list_{}".format(test_data[i])]=[]
globals()["test_calculation_{}".format(test_data[i])]=0
First, I created test_list_number and test_calculation_number as global variables.
Then I want to use this in for and use it for calculations.
The code I wrote here was made by simplifying the code I'm going to use.
How do I change the numbers in the two for statements below?
1
--------------Below is a code example. -------------
import pandas as pd
import numpy as np
X=list(np.random.random(100)*100)
Y=list(np.random.random(100)*100)
test_data= [2,5,7,8]
test_dict={(i,j):np.hypot(X[i]-X[j],Y[i]-Y[j]) for i in range(0,100) for j in range(0,100)}
test_df_data2={
'index' : [1,2,3],
'data1' : [3,5,6],
'data2' : [2,5,6]
}
test_df_data5={
'index' : [1,2,3],
'data1' : [8,3,1],
'data2' : [3,2,7]
}
test_df_2 =pd.DataFrame(test_df_data2)
test_df_5 =pd.DataFrame(test_df_data5)
for i in range(0,len(test_data)):
globals()["test_list_{}".format(test_data[i])]=[]
globals()["test_calculation_{}".format(test_data[i])]=0
for i in range(0, len(test_df_2 ) ):
test_list_2 .append((test_df_2 .data1[i],test_df_2 .data2 [i]))
for i in range(len(test_list_2 )):
test_calculation_2 = test_calculation_2 + test_dict[test_list_2 [i] ]
print( test_calculation_2)
Short answer, do not do this!
It is widely accepted to be a bad practice (see for example). You have a high risk of doing something difficult to debug, to overwrite existing variables, or to use the wrong namespace. In addition there are eventual pitfalls and lack of robust methods to do this.
Use a container instead.
You will have a shorter, cleaner, and easier to debug code.
Dictionaries are ideal for this:
# initialize
my_dfs = {}
# computation
for i in …:
my_dfs[f'df_computation_{i}'] = …
# access
my_dfs['df_computation_42']
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have written the following program in Python:
s = []
for e in random_key:
s = str(e)
print(s)
where the list random_key is
random_key = ['0011111011100101', '0000010111111011', '0011100110110100',
'1000010101010010', '0011001011001111', '1101101101110011',
'1100001111111011', '0000100000110100', '0101111010100101',
'1001100101100001']
The output of the program is
1111011010110011
1011000110011100
0011011001100010
0000011100100001
1111111010000100
0110110101100011
1011100011000101
1011101011100010
1101101101001010
1000011110110000
which is not correct. How can I fix the code?
If I am able to read your thoughts (not sure about that ..). Would you like them to 10 based numbers?
random_key = ['0011111011100101', '0000010111111011', '0011100110110100',
'1000010101010010', '0011001011001111', '1101101101110011',
'1100001111111011', '0000100000110100', '0101111010100101',
'1001100101100001']
numbers = [int(x, 2) for x in random_key]
print(numbers)
output
[16101, 1531, 14772, 34130, 13007, 56179, 50171, 2100, 24229, 39265]
Do you mean this?
s = list()
for e in random_key:
s.append(str(e))
print(s)
Returns:
['0011111011100101', '0000010111111011', '0011100110110100', '1000010101010010', '0011001011001111', '1101101101110011', '1100001111111011', '0000100000110100', '0101111010100101', '1001100101100001']
I have a list adImageList of dictionary items in following form:
[{'Image_thumb_100x75': 'https://cache.domain.com/mmo/7/295/170/227_174707044_thumb.jpg',
'Image_hoved_400x300': 'https://cache.domain.com/mmo/7/295/170/227_174707044_hoved.jpg',
'Image_full_800x600': 'https://cache.domain.com/mmo/7/295/170/227_174707044.jpg'},
{'Image_thumb_100x75': 'https://cache.domain.com/mmo/7/295/170/227_1136648194_thumb.jpg',
'Image_hoved_400x300': 'https://cache.domain.com/mmo/7/295/170/227_1136648194_hoved.jpg',
'Image_full_800x600': 'https://cache.domain.com/mmo/7/295/170/227_1136648194.jpg'},
{'Image_thumb_100x75': 'https://cache.domain.com/mmo/7/295/170/227_400613427_thumb.jpg',
'Image_hoved_400x300': 'https://cache.domain.com/mmo/7/295/170/227_400613427_hoved.jpg',
'Image_full_800x600': 'https://cache.domain.com/mmo/7/295/170/227_400613427.jpg'}]
I have iterator which suppose to add local URL under each image record after fetching it from web (fetching part works ok). So I'm using following code to append local URL to existing dictionary items:
for i, d in enumerate(adImageList):
file_name_thumb = '0{}_{}_{}'.format(i, page_title,'_thumb_100x75.jpg')
urllib.request.urlretrieve(d['Image_thumb_100x75'], file_name_thumb)
local_path_thumb = dir_path+file_name_thumb
adImageList.insert[i](1,{'Image_thumb_100x75_local_path_thumb':local_path_thumb}) # not working
file_name_hoved = '0{}_{}_{}'.format(i, page_title,'_hoved_400x300.jpg')
urllib.request.urlretrieve(d['Image_hoved_400x300'], file_name_hoved)
local_path_hoved = dir_path+file_name_hoved
adImageList.insert[i](3,{'Image_hoved_400x300_local_path_hoved':local_path_hoved}) # not working
file_name_full = '0{}_{}_{}'.format(i, page_title,'_full_800x600.jpg')
urllib.request.urlretrieve(d['Image_full_800x600'], file_name_full)
local_path_full = dir_path+file_name_full
adImageList.insert[i](5,{'Image_full_800x600_local_path_full':local_path_full}) # not working
Idea is to extend dict items in following manner which also explains numbers 1,3 and 5 in my code
{'Image_thumb_100x75': 'https://cache.domain.com/mmo/7/295/170/227_174707044_thumb.jpg',
'Image_thumb_100x75_local_path_thumb':local_path_thumb #1,
'Image_hoved_400x300': 'https://cache.domain.com/mmo/7/295/170/227_174707044_hoved.jpg',
'Image_hoved_400x300_local_path_hoved':local_path_hoved #3
'Image_full_800x600': 'https://cache.domain.com/mmo/7/295/170/227_174707044.jpg',
'Image_full_800x600_local_path_full':local_path_full #5}
But it's giving me error:
TypeError: 'builtin_function_or_method' object is not subscriptable
Most likely here's what you had in mind:
adImageList[i]['Image_thumb_100x75_local_path_thumb']=local_path_thumb
This adds key 'Image_thumb_100x75_local_path_thumb' to the ith dictionary on the list and sets its value to local_path_thumb. The purpose of 1,3,5 is still unclear.
python stack traces give line numbers for a reason, but my guess is this line:
adImageList.insert[i]
insert is a method
This question already has answers here:
How do I merge two dictionaries in a single expression in Python?
(43 answers)
Closed 7 years ago.
The question is
This is what I have so far:
dict(nafta_capitals) = canadian_capitals, mexican_capitals, us_capitals
Given three dictionaries, associated with the variables , canadian_capitals, mexican_capitals, and us_capitals, that map provinces or states to their respective capitals, create a new dictionary that combines these three dictionaries, and associate it with a variable , nafta_capitals.
You may need to use defaultdict-
Here nafta is used as key to the three ( canadian_capitals, mexican_capitals, us_capitals) as below-
>>>dic = defaultdict(list)
>>>lst = ['nafta1', 'canadian_capitals1', 'mexican_capitals1', 'us_capitals1', 'nafta2', 'canadian_capitals2', 'mexican_capitals2', 'us_capitals2']
>>>grouped_lst = [lst[i:i+4] for i in range(0,len(lst),4)]
>>>[['nafta1', 'canadian_capitals1', 'mexican_capitals1', 'us_capitals1'], ['nafta2', 'canadian_capitals2', 'mexican_capitals2', 'us_capitals2']]
>>>for i in grouped_lst:dic[i[0]]=i[1:]
>>>dic.items()
>>>[('nafta1', ['canadian_capitals1', 'mexican_capitals1', 'us_capitals1']), ('nafta2', ['canadian_capitals2', 'mexican_capitals2', 'us_capitals2'])]
>>>for i in dic.keys():print dic[i]
>>>['canadian_capitals1', 'mexican_capitals1', 'us_capitals1']
['canadian_capitals2', 'mexican_capitals2', 'us_capitals2']
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a csv file with the following data.
Column-1 Column-2 Column-3
bob sweet 4
alice uber 4.5
bob uber 4
alice sweet 4.5
razi fav 2.5
razi uber 3.5
bob fav 4
I want to convert it to a dictionary as shown,
A={'bob':{'sweet':'4', 'uber':'4', 'fav':'4'},
'alice':{'uber':'4.5', 'sweet':'4.5'},
'razi':{'fav':'2.5', 'uber':'3.5'}}
in python
For that i am willing to do like this..convert the csv to list like this and then get my output. I am unable to do so, coz keys are repeated as shown.
A={'bob':['sweet','4'],
'alice':['uber','4.5'],
'bob':['uber','4'],
'alice':['sweet','4.5'],
'razi':['fav','2.5'],
'razi':['uber','3.5'],
'bob':['fav','4']}
Can any one suggest a way to solve problem?
Assuming you don't have any space in your datas, and all your actual data rows have exactly 3 fields:
import logging
logging.basicConfig(level=logging.INFO) # <- in a real application,
# should be set application-wide
# from a config file
logger = logging.getLogger("CSV import")
result = {}
nlines = 0
ok = 0
warnings = 0
with open("my_file.csv") as f:
f.readline() # Skip header. Assuming only one line of heading
for row in (line.split() for line in f):
nlines += 1
try:
k1,k2, val = row
result.setdefault(k1,{})[k2] = val
ok += 1
except ValueError:
logger.warning("Format mismatch: %s", row)
warnings += 1
# what to do next?
logger.info("%d lines read. %d imported. %d warnings",nlines,ok,warnings)
from pprint import pprint
pprint(result)
Given your sample data file, this produces:
INFO:CSV import:7 lines read. 7 imported. 0 warnings
{'alice': {'sweet': '4.5', 'uber': '4.5'},
'bob': {'fav': '4', 'sweet': '4', 'uber': '4'},
'razi': {'fav': '2.5', 'uber': '3.5'}}
The trick here is to use setdefault to access to outer dictionary. It will either return the value if the key was already present -- or a new dictionary if this is the first time we encounter that key. After that, this is simply a matter of adding the value to the inner dictionary as usual.