Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5284

Python • Re: list/dict error - not understanding

$
0
0
This

mydata = ['AirTemp', ' 71.73']

is a list

First item in the list, mydata[0] = 'AirTemp'
Second item in the list, mydata [1] = '71.73'

This is a dictionary:
mydata = { 'AirTemp': '71.73'}

mydata['AirTemp'] = '71.73'

There is no mydata['71.73']

See more here: https://www.geeksforgeeks.org/differenc ... in-python/
Yes, I recall getting confused on this page. Once I opened up the link, I recognized it.

So [] is a list while {} is a dict? Correct?

Then why would there be a check for a dict in these lines of code:

Code:

if parts[0] == FIRST_LABEL:results = {}results[parts[0]] = parts[1]
if parts[0] equals HOT_FLUID_TEMP (which is correct) then results{} (It's telling the program that results is now a dict?) but then says to keep [1] which is the numeric value....Am I understanding that at that point, I have a dict of 4 numbers?
Here we have a list with 2 string values:

Code:

mydata = ['some name', 'some value']
mydata[0] contains string 'some name' and mydata[1] contains the string 'some value'

results = {} creates an empty dict.

For this

Code:

results[mydata[0]] = mydata[1]
We just replace the expression mydata[0] with what it holds, and we do the same with the mydata[1] which "translates" to

Code:

results["some name"] = "some value"
Now the dict results contains this:

Code:

{  "some value" : "some data"}
It just used item 0 and item 1 from the list to add an item to the dict where the item's key is "some name" and that item's value is "some value"

And that is the main difference between a list and a dict. In a list, you get the value by the items position in the list. But with a dict you use the key to get the value.

Statistics: Posted by memjr — Wed Apr 17, 2024 2:49 am



Viewing all articles
Browse latest Browse all 5284

Trending Articles