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 python assignment, and I`m stuck on step number 7. How would I solve this step? It involves counting the number of times a certain item appears in a list.
Link to assignment
Count how many of each alphabetic character.
Use a dictionary:
It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.
e.g {"Key1" : "Value 1", 1 : 2, "Key3" : 4, 5 : "Value5"}
In this case, for counting, we could set up the dictionary to be like this:
{character : # of times it has shown up} e.g {"a" : 7, "b" : 29}
How would we use a dictionary as a counter? Well, you see, they have this cool feature. If the Value of a Key is an int() or float(), you can use it like an int or float!
>>> example = {'letter' : 13}
>>> example['letter'] += 10
>>> example['letter']
23
>>> example['letter'] *= 1.02
>>> example['letter']
23.46
Knowing this, we could iterate through all the letters in a list or paragraph and either add them to the dictionary and set their value to 1 (if they have't been added) OR, if they have been added, just += 1 to their value.
Related
This question already has answers here:
How to get multiple max key values in a dictionary?
(3 answers)
Closed 2 years ago.
I know that this question looks like its been asked but this variation has not. I have a dictionary with the values {'John': 10, 'Chase': 11, 'Cole': '11'}. If i use the max function, I'll only get the first value with the max (Chase). However in my program, I need to get all of the values (Chase and Cole). Any help? I have 2 separate lists that are also combined into a dictionary. I have done:
for value in array1dictionary:
if value == max(array1list):
maxkeyarray.append(key)
but that does not work. Any advice?
You can try this:
dictt = {'John': 10, 'Chase': 11, 'Cole': '11'}
max_val = max(dictt.values(), key = lambda x: int(x))
maxkeyarray = [key for key in dictt if int(dictt[key]) == max_val]
print(maxkeyarray)
Output:
['Chase', 'Cole']
I have a series of dictionaries which each contain the same keys but their values are different i.e Age in dictionary 1 = 2, Age in dictionary 2 = 4 etc etc but they are broadly identical in structure.
what I would like to do is to randomly select one of these dictionaries and then assign specific values with the dictionary to variables. i.e python randomly chooses Dictionary 1 and then I then want to fill the dictAge variable with the age value from Dictionary 1.
import random
dictList = ['myDict', 'otherDict']
mydict = {
'age' : 10,
'other': "dummy data"
}
.
.
.
randomDict = random.choice(dictList)
dictAge = randomDict['age']
print(dictAge)
In the case of the code above what should happen is:
randomDict is assigned a random value from the distList variable (at the top). This sets which dictionary's values will be used going forward.
I next want the dictAge variable to then be assigned the age value from the selected dictionary. In this case (as mydict is was the only dictionary available) it should be assigned the age value of 10.
The error I am getting is:
TypeError: string indices must be integers
I know this is such a common error but my brain can't quite work out what the best solution is.
(Disclaimer: I haven't used python in ages so I know I am doing something really obviously silly but I can't quite work out what to do).
Right now, you are not actually using the definition of your dicts.
This is because dictList is comprised of strings: ['myDict', 'otherDict'].
So, when doing randomDict = random.choice(dictList), randomDict will either be the string 'myDict', or the string 'otherDict'.
Then you are doing randomDict['age'], which means you are trying to slice a string, with a string. As the error suggests, this can't be done and indices can only be ints.
What you want to do, is move the definition of the dictList to be after the definitions of your dicts, and include references to the dicts themselves, not strings. Something like:
mydict = {
'age' : 10,
'other': "dummy data"
}
.
.
.
dictList = [myDict, otherDict]
In the following piece of code:
dictAge = randomDict['age']
You are trying to index the name of dictionary variable (a string) returned by random.choice function.
To make it work you would need to do it using locals:
locals()[randomDict]['age']
or rather correct the dictList to contain the dictionaries instead of their names:
dictList = [myDict, otherDict]
In the latter case please note that myDict and otherDict should be declared before dictList.
This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 3 years ago.
I have a list of strings that I am trying to organize numerically it looks like this :
List=['Core_0_0.txt', 'Core_0_1.txt','Core_0_2.txt',...'Core_1_0.txt','Core_2_3.txt', ]
but when I sort it sorted(List)
It doesn't sort the list properly.
It's very important that I keep the values as strings and they must be ordered by the number; I.E. 0_1, 0_2,0_3....31_1, they all have Core_X_X.txt How would I do this.
If you can assume all your entries will look like *_N1_N2.txt, you can use the str.split method along with a sorting key function to sort your list properly. It might look something like this
sorted_list = sorted(List, key = lambda s: (int(s.split("_")[1]), int(s.split("_")[2].split(".")[0])))
Essentially, this internally creates tuples like (N1, N2) where your file is named *_N1_N2.txt and sorts based on the N1 value. If there's a tie, it will resort to the N2 value.
Your question is a possible duplicate of another question.
Which I am posting for you here again.
you just need to change 'alist' to your 'List'.
import re
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
(See Toothy's implementation in the comments)
'''
return [ atoi(c) for c in re.split(r'(\d+)', text) ]
alist=[
"something1",
"something12",
"something17",
"something2",
"something25",
"something29"]
alist.sort(key=natural_keys)
print(alist)
yields
['something1', 'something2', 'something12', 'something17', 'something25', 'something29']
Suppose ,I have a dictionary
key={'a':5}
Now ,I want to add values to it cumulatively without overwriting the current value but adding on to it.How to do it?
I am giving an instance:
for post in doc['post']:
if 'wow' in post:
value=2
for reactor in post['wow']['reactors']:
dict_of_reactor_ids.update({reactor['img_id']:value})
if 'sad' in post:
value=2
for reactor in post['sad']['reactors']:
dict_of_reactor_ids.update({reactor['img_id']:value})
Suppose if the dictionary is like this in first iteration
dict_of_reactor_ids={101:2,102:1}
and NOW I want to increase the value of 101 key by 3 ,then how to do that.
dict_of_reactor_ids={101:5,102:1}
Now in second iteration of post ,I want to add values to the current values in dictionary without overwriting the current value.
I have tried update method but I think it just updates the whole value instead of adding onto it.
Sounds like a typical case of Counter:
>>> from collections import Counter
>>> c = Counter()
>>> c["a"] += 1 # works even though "a" is not yet present
>>> c.update({"a": 2, "b": 2}) # possible to do multiple updates
{"a": 3, "b": 2}
In your case the benefit is that it works even when the key is not already in there (default value is 0), and it allows updates of multiple values at once, whereas update on a normal dict would overwrite the value as you've noticed.
You can also use defaultdict, it "defaults" when there is not yet an existing key-value pair and you still use the cumulative add +=:
from collections import defaultdict
dict_of_reactor_ids = defaultdict(int)
dict_of_reactor_ids[101] += 2
dict_of_reactor_ids[102] += 1
dict_of_reactor_ids['101'] += 3
print(dict_of_reactor_ids['101'])
5
total=0
line=input()
line = line.upper()
names = {}
(tag,text) = parseLine(line) #initialize
while tag !="</PLAY>": #test
if tag =='<SPEAKER>':
if text not in names:
names.update({text})
I seem to get this far and then draw a blank.. This is what I'm trying to figure out. When I run it, I get:
ValueError: dictionary update sequence element #0 has length 8; 2 is required
Make an empty dictionary
Which I did.
(its keys will be the names of speakers and its values will be how many times s/he spoke)
Within the if statement that checks whether a tag is <SPEAKER>
If the speaker is not in the dictionary, add him to the dictionary with a value of 1
I'm pretty sure I did this right.
If he already is in the dictionary, increment his value
I'm not sure.
You are close, the big issue is on this line:
names.update({text})
You are trying to make a dictionary entry from a string using {text}, python is trying to be helpful and convert the iterable inside the curly brackets into a dictionary entry. Except the string is too long, 8 characters instead of two.
To add a new entry do this instead:
names.update({text:1})
This will set the initial value.
Now, it seems like this is homework, but you've put in a bit of effort already, so while I won't answer the question I'll give you some broad pointers.
Next step is checking if a value already exists in the dictionary. Python dictionaries have a get method that will retrieve a value from the dictionary based on the key. For example:
> names = {'romeo',1}
> print names.get('romeo')
1
But will return None if the key doesn't exist:
> names = {'romeo',1}
> print names.get('juliet')
None
But this takes an optional argument, that returns a different default value
> names = {'romeo',2}
> print names.get('juliet',1)
1
Also note that your loop as it stands will never end, as you only set tag once:
(tag,text) = parseLine(line) #initialize
while tag !="</PLAY>": #test
# you need to set tag in here
# and have an escape clause if you run out of file
The rest is left as an exercise for the reader...