Accessing an index/value inside a key (Python) - python

I've got a dictionary with 18 different keys, each has 3 values inside (xPower, xPP and xAccuracy) each variable holds an int. How would I access one value from a certain key? For example, I want to take out the value of ScratchPower (40) for use elsewhere. After searching for over half an hour the most I have found is accessing all the values from a key:
print defMoves["Scratch"]
Here is my dictionary:
defMoves = {
"Scratch": [ScratchPower, ScratchPP, ScratchAccuracy],
"Air Slash": [Air_SlashPower, Air_SlashPP, Air_SlashAccuracy],
"Flare Blitz": [Flare_BlitzPower, Flare_BlitzPP, Flare_BlitzAccuracy],
"Growl": [GrowlPower, GrowlPP, GrowlAccuracy],
"Heat Wave": [Heat_WavePower, Heat_WavePP, Heat_WaveAccuracy],
"Ember": [EmberPower, EmberPP, EmberAccuracy],
"Shadow Claw": [Shadow_ClawPower, Shadow_ClawPP, Shadow_ClawAccuracy],
"Smokescreen": [SmokescreenPower, SmokescreenPP, SmokescreenAccuracy],
"Dragon Claw": [Dragon_ClawPower, Dragon_ClawPP, Dragon_ClawAccuracy],
"Dragon Rage": [Dragon_RagePower, Dragon_RagePP, Dragon_RageAccuracy],
"Scary Face": [Scary_FacePower, Scary_FacePP, Scary_FaceAccuracy],
"Fire Fang": [Fire_FangPower, Fire_FangPP, Fire_FangAccuracy],
"Flame Burst": [Flame_BurstPower, Flame_BurstPP, Flame_BurstAccuracy],
"Wing Attack": [Wing_AttackPower, Wing_AttackPP, Wing_AttackAccuracy],
"Slash": [SlashPower, SlashPP, SlashAccuracy],
"Flamethrower": [FlamethrowerPower, FlamethrowerPP, FlamethrowerAccuracy],
"Fire Spin": [Fire_SpinPower, Fire_SpinPP, Fire_SpinAccuracy],
"Inferno": [InfernoPower, InfernoPP, InfernoAccuracy],
}
Thanks

defMoves["Scratch"] returns a list so just index like you would any list:
defMoves["Scratch"][0] # first subelement -> ScratchPower
defMoves["Scratch"][1] # second subelement -> ScratchPP
defMoves["Scratch"][2] # third subelement -> ScratchAccuracy
......

defMoves["Scratch"] gets you back the value, which in this case is a list, associated with that key. To get a specific item from that list, you need to use a numeric index. So, for example, to get ScratchPower, you'd use defMoves["Scratch"][0].
That seems hard to keep track of, though, so you may want to use another dictionary inside each of these dictionaries. That'd look like
{"Scratch" : {"Power":40... }... }

Related

What does this piece of Python code do? I saw it and it confused me

capitals[add] = capitals.get(add, "?")
Im confused as to what that does. Can anyone explain to me what its doing?
The assignment in that code is equivalent to this alternative, which explicitly tests for the existence of the key held in the variable add in the dictionary:
if add not in capitals:
capitals[add] = "?"
The original code you asked about uses different logic by utilizing the dict.get method to get either the existing value (if there is one) for the key add, or the string "?" if that key doesn't exist in the dictionary. In either case, it unconditionally updates the dictionary (either with the same value it had, or the new default). Afterwards, you can be confident that add is always a key in the dictionary with some value.
A better solution than either your original or my alternative version of it above would be:
capitals.setdefault(add, "?")
This is likely to preform a little better because it's all in one method, so there's no need for the dictionary to need to hash the key twice.
Here's an example to show how the get function works on a dictionary. Let's say your dictionary looks like this:
capitals = {
'MA': 'Boston',
'RI': 'Providence',
'NY': 'Albany'
}
If you use the get function on a valid key, you'll get the value back. For example:
>>> add = 'RI'
>>> capitals.get(add, "?")
'Providence'
If you try the get function on a key that isn't present in the dictionary, then you will get back the missing key value (a '?' in your example).
>>> add = 'TX'
>>> capitals.get(add, "?")
'?'
So if you set capitals[add] = capitals.get(add, "?") it would either create a new key with a value of "?" (if the key doesn't exist) or update an existing key with the same value it already has.
There's other documentation on the web if you search for "python get function". Good luck!
Since you seem to be unable to understand the given response, I'll break it down for you.
The get() method of a dictionary does the following:
Checks the dictionary to see if the dictionary has a key corresponding to the first parameter. Then, it does one of the following:
If there is a key that matches the given one, then it returns the corresponding value.
If there is no matching key, then, if the second parameter is provided, it will return that value.
Now let's look at your question with the following two sample dictionaries:
capitals_1 = {
"UK": "London",
"USA": "Washington DC",
"India": "New Delhi"
}
capitals_2 = {
"Brazil": "Brasilia",
"Australia": "Canberra",
"Russia": "Moscow"
}
add = "India"
For capitals_1, "India" is already a key, so executing the above code will return the value corresponding to "India", which is "New Delhi".
For capitals_2, "India" is not a key, so executing the above code will return the default value specified, which is "?".
With these values obtained, the code then sets the value corresponding to "India" to whatever you got, so if "India" is already a key, then no change, but, if, like the second example, if India is not a key, then the dictionary will have the additional key-value pair of "India":"?".

Most pythonic way of iterating list items into a nested dict

I have a problem and I want to determine whether my approach is sound. Here is the idea:
I would be creating a primary dict called zip_codes, of which respective zipcodes (from a list) were the names of each of the nested dicts. Each would have keys for "members", "offices", "members per office"
It would look like this:
zips {
90219: {
"members": 120,
"offices": 18,
"membersperoffice": 28
},
90220: {
"members": 423,
"offices": 37,
"membersperoffice": 16
}
}
and so on and so forth.
I think I need to build the nested dicts, and then process several lists against conditionals, passing resulting values into the corresponding dicts on the fly (i.e. based on how many times a zip code exists in the list).
Is using nested dictionaries the most pythonic way of doing this? Is it cumbersome? Is there a better way?
Can someone drop me a hint about how to push key values into nested dicts from a loop? I've not been able to find a good resource describing what I'm trying to do (if this is, indeed, the best path).
Thanks.
:edit: a more specific example:
determine how many instances of a zipcode are in list called membersperzip
find corresponding nested dict with same name as zipcode, inside dict called zips
pass value to corresponding key, called "members" (or whatever key)
:edit 2:
MadPhysicist requested I give code examples (I don't even know where to start with this one and I can't find examples. All I've been able to do thus far is:
area_dict = {}
area_dict = dict.fromkeys(all_areas, 0) #make all of the zipscodes keys, add a zero in the first non-key index
dictkeys = list (area_dict.keys())
That gets me a dict with a bunch of zip codes as keys. I've discovered no way to iterate through a list and create nested dicts (yet). Hence the actual question.
Please don't dogpile me and do the usual stack overflow thing. This is not me asking anyone to do my homework. This is merely me asking someone to drop me a HINT.
:edit 3:
Ok. This is convoluted (my fault). Allow me to clarify further:
So, I have an example of what the nested dicts should look like. They'll start out empty, but I need to iterate through one of the zip code lists to create all the nested dicts... inside of zips.
This is a sample of the list that I want to use to create the nested dicts inside of the zips dict:
zips = [90272, 90049, 90401, 90402, 90403, 90404, 90291, 90292, 90290, 90094, 90066, 90025, 90064, 90073]
And this is what I want it to look like
zips {
90272: {
"members": ,
"offices": ,
"membersperoffice":
},
90049: {
"members": ,
"offices": ,
"membersperoffice":
}
}
....
etc, etc. ( creating a corresponding nested dict for each zipcode in the list)
After I achieve this, I have to iterate through several more zip code lists... and those would spit out the number of times a zip code appears in a given list, and then find the dict corresponding to the zip code in question, and append that value to the relevant key.
One I figure out the first part, I can figure this second part out on my own.
Thanks again. Sorry for any confusion.
You can do something like this:
all_areas = [90219, 90220]
zips = {zipcode: code_members(zipcode) for zipcode in all_areas}
def code_members(zipcode):
if zipcode == 90219:
return dict(members=120, offices=18, membersperoffice=28)
return dict(members=423, offices=37, membersperoffice=16)
I think I need to build the nested dicts, and then process several
lists against conditionals, passing resulting values into the
corresponding dicts on the fly (i.e. based on how many times a zip
code exists in the list).
Using the above approach, if a zipcode appears multiple times in the all_areas list, the resulting zip dictionary will only contain one instance of the zipcode.
Is using nested dictionaries the most pythonic way of doing this? Is
it cumbersome? Is there a better way?
May I suggest making a simple object that represents the value of each zipcode. Something simple like:
Using dataclass:
#dataclass.dataclass
class ZipProperties(object):
members: int
offices: int
membersperoffice: int
Using named tuple:
ZipProperties = collections.namedtuple('ZipProperties', ['members', 'offices', 'membersperoffice'])
You can then change the code_members function to this:
def code_members(zipcode):
if zipcode == 90219:
return ZipProperties(120, 18, 28)
return ZipProperties(423, 37, 16)
Addressing your concrete example:
determine how many instances of a zipcode are in list called membersperzip
find corresponding nested dict with same name as zipcode, inside dict called zips
pass value to corresponding key, called "members" (or whatever key)
membersperzip: typings.List[Tuple[int, int]] = [(90219, 54)]
for zip, members in membersperzip:
for zipcode, props in zips.items():
if zipcode == zip:
props.members = members
I would suggest you to append it when you have the actual value instead of initializing dictionary with empty values for each key. You have list of keys and I do not see why you want to put all of them to the dictionary without having value in the first place.
zips = [90272, 90049, 90401, 90402, 90403, 90404, 90291, 90292, 90290, 90094, 90066, 90025, 90064, 90073]
zips_dict = {}
for a_zip in zips:
if a_zip not in zips_dict:
# Initialize proper value here for members etc.
zips_dict[a_zip] = proper_value
If you insist to initialize dict with empty value for each keys, you could use this, which will also iterate through the list anyway but in python comprehension.
zips = [90272, 90049, 90401, 90402, 90403, 90404, 90291, 90292, 90290, 90094, 90066, 90025, 90064, 90073]
zips_dict = {
x:{
"members":None,
"offices":None,
"membersperoffice":None,
} for x in zips
}
Hope this helps

dict with one key and multiple values

I was wondering if there's a way for me to pull a value at a specific index. Let's say I have a key with multiple values associated with it. But in my dictionary I have multiple keys, each key with multiple values. I want to iterate through the keys and then each respective value associated with that key. I want to be able to pull the value at the first index and subtract it from the value at the second index.
d= {108572791: [200356.77, 200358], 108577388: [19168.7, 19169]}
output for key 108572791 would be -1.33
output for key 108577388 would be -.03
I've try reading up on dict and how it works apparently you can't really index it. I just wanted to know if there's a way to get around that.
for key, values in total_iteritems():
for value in values:
value[0]-value[1]:
Edit:
Since the question is way different now, I'll address the new subject:
d= {108572791: [200356.77, 200358], 108577388: [19168.7, 19169]}
for i in d:
print("Output for key ",str(i), "would be ",(d[i][1]-d[i][0]))
Output:
Output for key 108572791 would be 1.2300000000104774
Output for key 108577388 would be 0.2999999999992724
Original answer
Yes. When you have a dict containing a list as value if you want to obtain a specific value, then you need to address the index in the list. An example is:
a = {'Name':['John','Max','Robert']}
This means that:
print(a['Name'])
Output:
['John','Max','Robert']
Since ['Name'] is a list:
for i in range(len(a['Name'])):
print(a['Name'][i]
Output:
John #(Because it's the index 0)
Max #(Index = 1)
Robert #(Index = 2)
If you want a specific value (for instance 'Max' which is index = 1)
print(a['Name'][1]
Output:
Max
Depends on how many values in key obvious but this does the trick:
for x in d:
print(x)
print(d[x][0]-d[x][1])
You can use list of tuples if you want to use indexing.
d= [(108572791,[200356.77, 200358]), (108577388,[19168.7, 19169)]
for tuple in my_list:
print(tuple[0])
for value in tuple[1]:
print(value)

Thingspeak: Parse json response with Python

I would like to create an Alexa skill using Python to use data uploaded by sensors to Thingspeak. The cases where I only use one specific value is quite easy, the response from Thingspeak is the value only. When I want to use several values, in my case to sum up the athmospheric pressure to determine tendencies, teh response is a json object like this:
{"channel":{"id":293367,"name":"Weather Station","description":"My first attempt to build a weather station based on an ESP8266 and some common sensors.","latitude":"51.473509","longitude":"7.355569","field1":"humidity","field2":"pressure","field3":"lux","field4":"rssi","field5":"temp","field6":"uv","field7":"voltage","field8":"radiation","created_at":"2017-06-25T07:35:37Z","updated_at":"2018-08-04T12:11:22Z","elevation":"121","last_entry_id":1812},"feeds":
[{"created_at":"2018-10-21T18:11:45Z","entry_id":1713,"field2":"1025.62"},
{"created_at":"2018-10-21T18:12:05Z","entry_id":1714,"field2":"1025.58"},
{"created_at":"2018-10-21T18:12:25Z","entry_id":1715,"field2":"1025.56"},
{"created_at":"2018-10-21T18:12:45Z","entry_id":1716,"field2":"1025.65"},
{"created_at":"2018-10-21T18:13:05Z","entry_id":1717,"field2":"1025.58"},
{"created_at":"2018-10-21T18:13:25Z","entry_id":1718,"field2":"1025.63"}]
I now started with
f = urllib.urlopen(link) # Get your data
json_object = json.load(f)
for entry in json_object[0]
print entry["field2"]
The json object is a bit recursive, it is a list containing a list with an element with an array as the value.
Now I am not quite sure how to iterate over the values of the key "field2" in the array. I am quite new to Python and also json. Perhaps anyone can help me out?
Thanks in advance!
This has nothing to do with json - once the json string parsed by json.load(), what you get is a plain python object (usually a dict, sometimes a list, rarely - but this would be legal - a string, int, float, boolean or None).
it is a list containing a list with an element with an array as the value.
Actually it's a dict with two keys "channel" and "feeds". The first one has another dict for value, and the second a list of dicts. How to use dicts and lists is extensively documented FWIW
https://docs.python.org/3/tutorial/datastructures.html#dictionaries
https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
https://docs.python.org/3/tutorial/introduction.html#lists
https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range
Here the values you're looking for are stored under the "field2" keys of the dicts in the "feeds" key, so what you want is:
# get the list stored under the "feeds" key
feeds = json_object["feeds"]
# iterate over the list:
for feed in feeds:
# get the value for the "field2" key
print feed["field2"]
You have a dictionary. Use key to access the value
Ex:
json_object = {"channel":{"id":293367,"name":"Weather Station","description":"My first attempt to build a weather station based on an ESP8266 and some common sensors.","latitude":"51.473509","longitude":"7.355569","field1":"humidity","field2":"pressure","field3":"lux","field4":"rssi","field5":"temp","field6":"uv","field7":"voltage","field8":"radiation","created_at":"2017-06-25T07:35:37Z","updated_at":"2018-08-04T12:11:22Z","elevation":"121","last_entry_id":1812},"feeds":
[{"created_at":"2018-10-21T18:11:45Z","entry_id":1713,"field2":"1025.62"},
{"created_at":"2018-10-21T18:12:05Z","entry_id":1714,"field2":"1025.58"},
{"created_at":"2018-10-21T18:12:25Z","entry_id":1715,"field2":"1025.56"},
{"created_at":"2018-10-21T18:12:45Z","entry_id":1716,"field2":"1025.65"},
{"created_at":"2018-10-21T18:13:05Z","entry_id":1717,"field2":"1025.58"},
{"created_at":"2018-10-21T18:13:25Z","entry_id":1718,"field2":"1025.63"}]}
for entry in json_object["feeds"]:
print entry["field2"]
Output:
1025.62
1025.58
1025.56
1025.65
1025.58
1025.63
I just figured it out, it was just like expected.
You have to get the entries array from the dict and than iterate over the list of items and print the value to the key field2.
# Get entries from the response
entries = json_object["feeds"]
# Iterate through each measurement and print value
for entry in entries:
print entry['field2']

Python Dictionary -index numbering is different every time

I'm using python 2.7\ Linux
I have api result (see below):
{"id":"137","iv":0,
"components":[{"id":"928","type":"IDUGW","creation_date":"2016-05-04 08:10:38.0","update_date":"2016-05-04 08:10:38.0","unit_id":"137","serial_number":"00000000501C8349"},
{"id":"927","type":"IDU","creation_date":"2016-05-04 08:10:37.0","update_date":"2016-05-04 08:10:37.0","unit_id":"137","serial_number":"00000000501C8268"},
{"id":"930","type":"Battery","creation_date":"2016-05-04 08:10:40.0","update_date":"2016-05-04 08:10:40.0","unit_id":"137","serial_number":"00000000501C802A"}
,{"id":"929","type":"Panel","creation_date":"2016-05-04 08:10:39.0","update_date":"2016-05-04 08:10:39.0","unit_id":"137","serial_number":"00000000501C810B"}],
"creation_date":"2016-05-04 08:10:41.0",
"update_date":"2016-05-04 08:10:41.0",
"serial_number":"0011",
"phone_number":"972528745028",
"owner_phone":"9720545555554"}
if i understand it right, i have dictionary inside dictionary ( 2nd line "component" is another dictionary which has 4 key\values in it)
I'm trying to check if in dictionary the "type" equals to parameter i give.
Code:
if (MyDictionary[u'components'][0][u'type'] <> lRestParams['type4']):
i have 4 index (0,1,2,3)
sometimes the "if" pass, and sometimes the index is changed (when rebuilding everything) and it fails
how can i compare type4 to MyDictionary[u'components'][one of index][u'type']
In addition i need to compare after that that the value of the key = value4
so it means that if we check index x than key and value should be checked there.
Hope not to complicated
Thanks in advance
Ohad
Instead of giving the index number, you can loop through the component values to do the comparision.
for keys in data['components']:
if keys['type'] == "IDUGW":
print "matched"

Categories

Resources