Indexing with string? [Python] - python

I am learning python this semester and I came across some code I do not understand well.
firstVal = examples[0][firstName]
where examples is list of dictionary
and firstName is a Str
Could someone help explain to me what it is doing?
Thanks!

Alright, so basically what it is doing is it is taking the first dictionary from the list of dictionaries, and accessing the value in the key for firstName.
For ex:
examples is some thing like:
[{'John': 'Doe', 'Jack': 'Peterson', 'Jake': 'Paul'}, {'Martin': 'Richardson', 'Luke': 'Skywalker', 'Logan': 'Paul'}]
Doing examples[0], get's you the first element of that list, which is: {'John': 'Doe', 'Jack': 'Peterson', 'Jake': 'Paul'}
Now, let's say firstName = 'Jack'.
Then, examples[0][firstName] is the same as examples[0]['Jack'] which is 'Peterson' because the value for the key 'Jack' is 'Peterson'
Please tell me if you need me to elaborate more ;)

The examples[0] is getting the first dictionary in the list of dictionaries examples. Then it is accessing the key defined by the string firstName.
For example,
examples = [{'1':2, '3':4}, {'5':6, '7':8}]
firstName = '1'
firstVal = examples[0][firstName] # will output 2

Let's take a look at it closely.
If examples is a list of dictionaries, then examples[0] must be the first dictionary in that list.
Then, we look for the key firstName in that dictionary.
We finally assign this value to firstVal.
So in a sentence, this line takes the first dictionary in the list, finds the value of the key firstName, and assigns it to firstVal.

Related

Add list data to a dictionary

So I have a dictionary
dict={'Andrew':5, 'Brian':3, 'Clive':2, 'David':4}
it contains the names of volunteers and the number of times that they have volunteered for a particular duty. The dictionary is regularly updated by providing both the dictionary and a list to a function upd.
For the current update the following list has been declared - each name represents a new volunteer session:
ulist = ['Brian', 'David', 'Peter']
Write and demonstrate the function upd. Any ideas where to start
I have
def upd(lst):
I know its not much, but I am just learning about lists and dictionaries.
TIA
David.
EDIT:
My apologies, I should have been more specific
the upd function should create the dictionary and append/increment when a user is found, if not, it should create new user
Here is what I imagine your requirements are:
If a name in ulist is already in the dictionary, increment the value associated with it, otherwise create an entry for the name and initialize the value to 1.
This code is quite simple really. Just iterate through each name in ulist and check to see if it is in my_dictionary, if not then add it, if so then increment it.
my_dictionary = {'Andrew':5, 'Brian':3, 'Clive':2, 'David':4}
ulist = ['Brian', 'David', 'Peter']
def udp(lst):
for name in lst:
if name in my_dictionary:
my_dictionary[name] += 1
else:
my_dictionary[name] = 1
udp(ulist)
print(my_dictionary)
Results:
{'Andrew': 5, 'Brian': 4, 'Clive': 2, 'David': 5, 'Peter': 1}
Note: You named your dictionary dict which is technically a keyword in Python so I recommend changing it to something like my_dictionary as shown in my example.

search through a nested dictionary and record the steps

say I have a dictionary like this:
profile = {'Person':{'name':['John'], 'Description':['smart']}}
I am looking for a piece of code that searches for 'John', and 'Description', but doesn't know where they are in the nested dictionary. I also want to the code to print something like this:
John is located in the value of profile['Person']
Description is located in the key of profile['Person']
How can I do that? Any help will be appreciated. Thank you
Learn how to iterate through a nested dictionary. In Python Dictionary, items() method is used to return the list with all dictionary keys with values. Indexing [ ] is used to access an element of a nested dictionary
profile = {'Person':{'name':['John'], 'Description':['smart']},'Person1':{'name':['John1'], 'Description':['smart1']}}
for p_id, p_info in profile.items():
for key in p_info:
if p_info[key][0] == "John":
print(p_info[key][0],"is located in the value of profile['",p_id,"']")
if p_info[key][0] == "smart":
print(p_info[key][0],"is located in the value of profile['",p_id,"']")

What is the difference between these two pieces of code concerning lists nested inside dictionaries?

I am learning python by reading the 'Python Crash Course' book so I'm still a beginner, what I want to know is the difference between these two pieces of code as they both seem to be the same to me but give different results.
names={
'first' : ['john','mike'],
}
for name in names.keys():
print(name[1])
This gives the result 'i'.
names={
'first' : ['john','mike'],
}
for name in names.keys():
print(names[name][1])
This gives my expected result; 'mike'.
Any help would be appreciated.
names.keys() will return all keys of the names dictionary. Hence the only key is just: first.
for name in names.keys() will go through the keys one by one, in this case it will only observe the single key above.
Thus ... name here stores the value "first"
"first"[1] will return 'i' and names['first'] will return ['john','mike'], hence names['first'][1] will return "mike" (the second element of that list)
In both cases, name refers to the (only) key in names, the string 'first'.
In the first loop, you print 'first'[1], which is 'i'.
In the second loop, you use the name to get a value from names; names[name] == ['john', 'mike'], so names[name][1] is ['john', 'mike'][1] == 'mike'.
names={
'first' : ['john','mike'],
}
for name in names.keys():
print(name[1])
First names is a dictionary which uses keys, not indexes. The 'key' for the dictionary in this example is first. Lets look at the dictionary:
>>> names
{'first': ['john', 'mike']}
We can see that there is one key first and that key has a list as the value. The list has two items john and mike.
When you do the for loop, you are iterating over each item in the dictionary. Specifically in your case, you are iterating over the keys. In this example there is only one key: first.
One thing that might be confusing you is you are using the variable name. Let's change it to i for the sake of example:
for i in names.keys():
print(i)
This will return first because that is the only key in the dictionary. You can replace i with (almost) any variable name you want.
So we have a str with the value of first and we want the 2nd character from that string. Remember, python starts at 0, so [1] is the 2nd character of the string first which is i.
Now, in the second code block, you have names[name][1]]. Remember that the names dictionary has the value {'first': ['john', 'mike']}. Again, let's change the word name to i to help see what's happening:
for i in names.keys():
print(names[i][1])
Again, the only key we have is first, so when the for loop iterates, it will go i == first, then end. Lets try this:
>>> names['first']
['john', 'mike']
This returns a list of the two names. If we take the first value of the list with >>> names['first'][1] we get mike.
So, in summary, in the first example you are taking a slice of the key which is a str, and in the second example you are returning the first element of the value of the dictionary of the given key.
When you call names.keys(), the function returns a list with all the keys in your dictionary. When you run a loop, name will be the elements of your list, the string "first" in that case. So, when you call name[1], it's the same as calling "first"[1], which will return the second character of the string: "i".
In the second code, when you call names[name], it's the same as calling names["first"], which returns a list(['john','mike']) and then you can print the second element of your list ("mike")
Try to understand this example:
>>> names = {'first': ['john', 'mike']}
>>> for key in names.keys():
... print(f'Current key is "{key}"')
... print(f'Second element of "{key}" is "{key[1]}"')
... print(f'Value of key "{key}" is "{names[key]}"')
... print(f'Second element of "{names[key]}" is "{names[key][1]}"')
...
Current key is "first"
Second element of "first" is "i"
Value of key "first" is "['john', 'mike']"
Second element of "['john', 'mike']" is "mike"

Using append to get data from a nested list

Currently my code is like this:
.append("Last Name {}, First Name {} Stats: {}".format(result["L_Name"], result["F_Name"], result["Stats"]))
this code works but the output isn't exactly the ones I want the code to display.
the problem is that the Stats has another list
L_Name: Doe
F_Name: John
Contribution:
Month
Value
Returns
is there a way to just pick out only the Value from the Stats by just adding or changing something in my append?
specifically in this part?
, result["Stats"]))
If you are only after one value of Stats, you can get the value at a certain index. Assuming Value is at index 1 and Stats is a standard Python list:
, result["Stats"][1]))
Notice that you can access the items of the JSON structure in the format string itself. This is clearer than using positional arguments if the format string is very complicated. Additionally, you can pass the whole dictionary into format_map:
l.append("Last Name {L_Name}, First Name {F_Name} Stats: {Stats[Value]}"
.format_map(result))
(In Python 2, format_map doesn't exist, use format(**result) instead.
In the future please consider posting working code only so we can reproduce your issue. I am going to assume result['stats'] is a dictionary and the bulleted list are key:value pairs.
You can access the "Contribution" key of your result["Stats"] dictionary which results in list. You can then slice the second element of the list with [1].
_.append("Last Name {}, First Name {} Stats: {}".format(
result["L_Name"],
result["F_Name"],
result["Stats"]["Contribution"][1]))
This assumes result['stats'] looks like:
result['stats'] = {
'L_Name': 'Doe',
'F_Name': 'John',
'Contribution': [Month, Value, Returns]}
Thanks everyone I was able to get a hint from your answers
result["Stats"]["Contribution"][1]
worked well for me

If 'some element' in a specific position of a list of tuples

I have a list of tuples:
MyList = [('name1', 'surname1', 'age1'), ('name2', 'surname2', 'age2'), ...]
I would like to make a check "if 'name2' in MyList, something like:
if 'name2' in MyList[?][0]:
print "do something"
If I would write if 'name2' in MyList[0] I would be accessing the element ('name1', 'surname1', 'age1') while what I meant is to access the element at position 0 of every tuple in the list. I guess there is a syntaxis to do that but I'm a newbie and cannot find it online myself, can anyone help me with this?
You can use any function and a generator function, like this
if any("name2" in name for name, surname, age in my_list):
# do something
Here all the elements of tuples are unpacked to name, surname, age while iterating. So, we can simply check if name2 is in name. This is the same as writing
if any("name2" in current_item[0] for current_item in my_list):
This will be efficient, as it yields True immediately after there is a match, rest of the items need not be checked.
If you are looking for a way to compare two strings, you should be using == operator, like this
if any("name2" == name for name, surname, age in my_list):
# do something
Sounds that you could benefit from using dictionaries:
my_dict = dict( (x[0],(x[1],x[2])) for x in MyList)
Then you can check for existence 'names2' in my_dict and also access directly the data my_dict['names2']
I am not sure if this is the most efficient method, but you could use this.
>>>MyList = [('name1', 'surname1', 'age1'), ('name2', 'surname2', 'age2'), ...]
>>> if 'name2' in zip(*MyList)[0]:
#do something.
The point is it creates a transpose of the original list. Caveat: All tuples have to be of same length to avoid data loss.
EDIT: Official docs for zip.
Official docs for * operator used in unpacking argument lists.

Categories