Nice to meet you all.
I'm new to Python and I've a "Maze solving" project. The project itself is a bit confusing and Professor wants users to use List for such tasks. The problem is I'm using dictionary to store input values instead of lists because I find dictionaries easier to work with in C#.
This is how I'm storing data:
ArcsDict.update({'Arc' + str(InputNum) : {'StartPoint': StartPoint, 'EndPoint': EndPoint, 'Price': Price}} )
This is how the dictionary looks:
{"Arc1": { "StartPoint" : 1, "EndPoint" : 2, "Price" : 10 }, "Arc2":{"StartPoint" : 3, "EndPoint" : 5, "Price" : 15 }}
Now I want to get only StartPoints and EndPoints from the dictionary and add them to another dictionary called NodesDict
for val in ArcsDict.keys():
for value in ArcsDict[val].keys():
print ArcsDict[val][value]
NodesDict.update({'Nodes' + str(InputNum) : {'XPoint': ArcsDict[val][value], 'YPoint': ArcsDict[val][value] }})
The above code "for loop" stuff sometimes makes sense to me and sometimes it doesn't but is there any way I can ONLY get the StartPoints and EndPoints from each Arc and add them to NodesDict then print the points as:
(0, 0)
(1, 3)
We are ONLY allowed to use default Python modules. Any help will be appreciated!
Edit: If anyone could explain how dictionary works in Python in a bit detail that would be appreciated as well! I would like to convince my professor to use dictionary instead of lists while making it sound easier and understandable at the same time.
Related
Eg:
ECE_student_list = [['section-1', [["sai",'science'], ["rama",'maths']]],
['section-2', [["seetha",'science'], ["ravana",'maths']]]]
I have to print student name and subject by passing key as section name.
for Eg : if the key is 'section-1' first student then it should print "sai",'science'
second student ,then it should print "rama",'maths'
please share the logic in python.
Won't share the code directly. That you have to learn and experiment on your own. Although I can tell you what you can expect as your output.
You can create a dictionary in python and add section-1, section-2 as the keys and the list of students as value for each key.
Your dictionary structure will be something like this:
{
'section-1' : [
{'sai':'science'},
{'rama':'math'}
],
'section-2':[
{'sai':'science'},
{'rama':'math'}
]
}
I'm trying to extract data from a JSON file with Python.
Mainly, I want to pull out the date and time from the "Technicals" section, to put that in one column of a dataframe, as well as pulling the "AKG" number and putting that in the 2nd col of the dataframe. Yes, I've looked at similar questions, but this issue is different. Thanks for your help.
A downNdirty example of the JSON file is below:
{ 'Meta Data': { '1: etc'
'2: etc'},
'Technicals': { '2017-05-04 12:00': { 'AKG': '64.8645'},
'2017-05-04 12:30': { 'AKG': '65.7834'},
'2017-05-04 13:00': { 'AKG': '63.2348'}}}
As you can see, and what's stumping me, is while the date stays the same the time advances. 'AKG' never changes, but the number does. Some of the relevant code I've been using is below. I can extract the date and time, but I can't seem to reach the AKG numbers. Note, I don't need the "AKG", just the number.
I'll mention: I'm creating a DataFrame because this will be easier to work with when creating plots with the data...right? I'm open to an array of lists et al, or anything easier, if that will ultimately help me with the plots.
akg_time = []
akg_akg = []
technicals = akg_data['Technicals'] #akg_data is the entire json file
for item in technicals: #this works
akg_time.append(item)
for item in technicals: #this not so much
symbol = item.get('AKG')
akg_akg.append(symbol)
pp.pprint(akg_akg)
error: 'str' object has no attribute 'get'
You've almost got it. You don't even need the second loop. You can append the akg value in the first one itself:
for key in technicals: # renaming to key because that is a clearer name
akg_time.append(key)
akg_akg.append(technicals[key]['AKG'])
Your error is because you believe item (or key) is a dict. It is not. It is just a string, one of the keys of the technicals dictionary, so you'd actually need to use symbols = technicals[key].get('AKG').
Although Coldspeed answer is right: when you have a dictionary you loop through keys and values like this:
Python 3
for key,value in technicals.items():
akg_time.append(key)
akg_akg.append(value["akg"])
Python 2
for key,value in technicals.iteritems():
akg_time.append(key)
akg_akg.append(value["akg"])
If I had the following code
buttonParameters = [
("button1", "button1.png"),
("button2", "button2.png"),
("button3", "button3.png"),
("button4", "button4.png"),
("button5", "button5.png"),
]
how would I go about accessing "button1" from buttonParameters.
Also, what type of list structure is this? I was reccomended using it, but I'm not sure I know what it's name is, and would like to search some to understand it more.
It seems like you are trying to retrieve a Value from a mapping, given a Key.
For this you are using a List when you should be using a Dictionary:
buttonParameters = {
"button1": "button1.png",
"button2": "button2.png",
"button3": "button3.png",
"button4": "button4.png",
"button5": "button5.png",
}
buttonParameters['button1'] #=> "button1.png"
A solution involving a List traversal to extract a value has linear worst-case performance whilst dictionary retrieval is amortised constant time.
You can convert your list of tuples into the above dictionary with:
buttonParameters = dict(buttonParameters)
This is different from retrieving variable/object name at run time.
2G_Functions={'2G_1':2G_f1,'2G_2':2G_f2}
3G_Functions={'3G_1':3G_f1,'3G_2':3G_f2}
myFunctionMap=[2G_Functions,3G_Functions]
for i in myFunctionMap:
print i.??? "\n"
for j in i:
print str(j)
I want the output look like below.
2G_Functions:
2G_1
2G_2
3G_Functions:
3G_1
3G_2
How can I get the name of dictionary variable in my code?I dont know which I am calling in the loop to know its name beforehand.
Despite the pessimism of the other answers, in this particular case you actually can do what you're asking for if there are no other names names assigned to the objects identified by G2_Functions and G3_Functions (I took the liberty of fixing your names, which are not valid Python identifiers as given.) That being said, this is a terrible, terrible, terrible idea and you should not do it, because it will eventually break and you'll be sad. So don't do it. Ever.
The following is analogous to what you're trying to do:
alpha = {'a': 1, 'b': 2}
beta = {'c': 2, 'd': 4}
gamma = [alpha, beta]
listOfDefinedLocals = list(locals().iteritems())
for x, y in listOfDefinedLocals:
if y is gamma[0]: print "gamma[0] was originally named " + x
if y is gamma[1]: print "gamma[1] was originally named " + x
This will output:
gamma[1] was originally named beta
gamma[0] was originally named alpha
I accept no responsibility for what you do with this information. It's pretty much guaranteed to fail exactly when you need it. I'm not kidding.
You can't. The myFunctionMap list contains the objects, not the name attached to them 2 lines above. BTW, calling a list variable "map" isn't a good practice, maps are usually dictionaries.
You can't start a variable name with a digit, so 2G_Functions and 3G_Functions won't work.
You can sidestep the problem by creating a dictionary with appropriate names
e.g.
myFunctionMap = {
"2G_Functions" : { ... },
"3G_Functions" : { ... },
}
for (name, functions) in myFunctionMap.iteritems():
print name
for func in functions.keys():
print func
In short, you can't.
In longer, it is sort of possible if you poke deep into, I think, the gc module (for the general case) or use locals() and globals()… But it's likely a better idea to simply define the list like this:
myFunctionMap = [ ("someName", someName), … ]
for name, map in myFunctionMap:
print name
…
Try making your list of lists as a list of strings instead:
d2G_Functions={'2G_1':"2G_f1",'2G_2':"2G_f2"}
d3G_Functions={'3G_1':"3G_f1",'3G_2':"3G_f2"}
myFunctions=["2G_Functions","3G_Functions"]
for dict_name in myFunctions:
print dict_name
the_dict = eval("d"+dict_name)
for j in the_dict:
print str(j)
(I changed the name of your original variables since python identifiers cannot begin with a digit)
this is my code :
vars_ = {
'attackUp':attackUp,'defenceUp':defenceUp,'magicUp':magicUp,'attType':attType,'weightDown':weightDown,
'accAttackSword':accAttackSword,'accAttackSaber':accAttackSaber,'accAttackAx':accAttackAx,
'accAttackHammer':accAttackHammer,'accAttackSpear':accAttackSpear,'accAttackFight':accAttackFight,
'accAttackBow':accAttackBow,'accAttackMagicGun':accAttackMagicGun,'accAttackMagic':accAttackMagic,
'mStrInstrument':mStrInstrument,'mStrCharms':mStrCharms,'accDefencePhy':accDefencePhy,
'accDefenceMag':accDefenceMag,'accWeight':accWeight,'bookTurn':bookTurn,'bookAttackPhy':bookAttackPhy,
'bookAttackMag':bookAttackMag,'bookStrInstrument':bookStrInstrument,'bookStrCharms':bookStrCharms,
'bookDefencePhy':bookDefencePhy,'bookDefenceMag':bookDefenceMag,'bookWeight':bookWeight,'name':name,
'plvl':plvl,'str':str,'ski':ski,'mag':mag,'spd':spd,'locX':locX,'locY':locY,'wName':wName,
'wAttack':wAttack,'wDefence':wDefence,'wWeight':wWeight,'wType':wType,'target':target,'title':title,
'uname':uname,'cUrl':cUrl,'mbCnt':mbCnt
}
oh my god , I spent a lot of time on this work , and maybe have more Variable to be added later ,
any easy way to do this ,
thanks
I would stop and consider why you are doing this. I can't help but think its not necessary.
Even if you decide this is necessary (which i doubt) - You are pretty much recreating globals(). Type that into your interpretter and see if you still want to do this.
Organize it further like senderle suggested in your other post. And maybe post a broader question with help for organizing your project.
The first thing I would do is reformat that dictionary so there is one entry per line:
vars_ = {
'attackUp' : attackUp,
'defenceUp' : defenceUp,
'magicUp' : magicUp,
'attType' : attType,
'weightDown': weightDown,
# and so on
}
I have also lined up the columns so the whole list reads more easily.
You could make an array of variable names and pull them out of the locals dictionary.
x, y, z = 5, 10, 20
l = locals()
d = {}
for v in ['x', 'y', 'z']:
d[v] = l[v]
# d = {'y': 10, 'x': 5, 'z': 20}
locals might work on it's own too if you're just wanting to look it up as a string.
attUp = locals()['attackUp']
I totally agree with #miku - look at how you are using the values and seriously refactor.
For example, a Character has Attributes (physical_attack, physical_defence, magic_attack, magic_defence, weight, speed) and Items; Weapons are Items, Swords and Axes and Spears and Bows are Weapons, a Saber is a Sword. Unarmed is a special default Weapon. Charms are Items, but apparently Books and StringedInstruments are Weapons?? Items have Attributes which are added to a Character's Attributes while equipped. Character also has level, location, target, and an accuracy rating for each weapon type (can a Weapon have an accuracy-modifier?).
If you break it down into a class hierarchy this way, it should be much easier to keep track of what you are doing.