Let's say I have accessed my dictionary keys using print (hamdict.keys())
Below is a sample output:
I know my dictionary list has a length of 552 elements. I want to randomly select one "key" word from my list and assign it to the variable "starter". I tried to do this with the code below (note: I have a dictionary called hamdict):
random_num = random.randint(0, len(hamdict.keys())-1)
print (random_num)
print (hamdict.keys()[random_num])
I'm able to get a value for random_num so that seems to work. But the second print returns the following error:
How can I fix my code?
my_dictionary.keys() returns a generator-like object, not a list. You can probably get what you want by converting it to a list first
print(list(hamdict.keys())[random_num])
Try this:
random.sample(hamdict.keys(),1)[0]
The sample() function randomly selects a given number of items from a list or iterator. Contrary to the choice function, it supports iterators so you don't need to make a list out of the keys beforehand. The result is a list so you need to get its first item from the output (hence the [0]).
Related
I am trying to utilize list comprehension to populate a new list, which is the length of text in a DataFrame column.
So if the text is "electrical engineer", it should output 19 etc. Instead, it just fills the list with None values
I have written out list comprehension below
all_text_length = [all_text_length.append(len(i)) for i in data['all_text']]
Expecting output of integer but its None
As a workaround, I am currently using (successfully)
[all_text_length.append(len(i)) for i in data['all_text']]```
Read the documentation on append: it works in-place. There is no returned value. What you've written is essentially
all_text_length = [None for i in data['all_text']]
It appears that you're trying to make a list comprehension to entirely change your list. Try this:
all_text_length = [len(i) for i in data['all_text']]
If you just need the lengths in a convenient form, would it do to form a new column? Simply apply len to the df column.
The value before the "for" statement in the list comprehension, will be added to the list. If you place a statement in there, like
all_text_length.append(len(i)
, the return value of that function will be added. Because .append() doesnt have areturn-statement in it, you get the value None as return type, wich will be added to your list.
Use the code #Prune recommended and it should work as you want.
You are trying to append to the same list on which you are doing list comprehension. Since the append returns a None type, you are getting None. The below code should work,
all_text_length = map(len, data['all_text'])
map is a function that takes another function (first argument) and applies it to every element in an iterable (second argument) and returns a list of the results.
I am trying to do something pretty simple but cant seem to get it. I have a dictionary where the value is a list. I am trying to just sum the list and assign the value back to the same key as an int. Using the code below the first line doesn't do anything, the second as it says puts the value back but in a list. All other things ive tried has given me an error can only assign iterable. As far as i know iterables are anything that can be iterated on such as list and not int. Why can I only use iterable and how can i fix this issue ? The dict im using is here (https://gist.github.com/ishikawa-rei/53c100449605e370ef66f1c06f15b62e)
for i in dict.values():
i = sum(i)
#i[:] = [sum(i) / 3600] # puts answer into dict but as a list
You can use simple dictionary comprehension if your dict values are all lists
{k:sum(v) for k, v in dict.items()}
for i in dikt.keys():
dickt[i] = sum(dict[i]))
btw, dict is a type. best not to use it as a variable name
Here is a simple nested dictionary:
wordFrequency = {'bit':{1:3,2:4,3:19,4:0},'red':{1:0,2:0,3:15,4:0},'dog':{1:3,2:0,3:4,4:5}}
I am trying to work out the difference between what these two pieces of code do:
for word, innerDictionary in wordFrequency.iteritems():
for fileNum, appearances in innerDictionary.iteritmes():
and
for fileNum, appearances in wordFrequency.get(word, {}).iteritems():
I know the first allows me to assign the keys and values of the inner dictionary to fileNum and appearances respectively.
However, I am unclear as to if the second piece of code does the same?
The following command :
for fileNum, appearances in wordFrequency.get(word, {}).iteritems():
Will give you only one value (of nested dictionaries) , but if you want it have a same effect like your preceding code ,As the get()'s function first argument must be a key of the dictionary you need to get the keys and put that code in a loop :
for word in wordFrequency.keys() :
for fileNum, appearances in wordFrequency.get(word, {}).iteritems():
I have a dictionary that needs its values to be 2D lists. I am having trouble adding these second values to a key. I have two lists, the first a list of values then a list of keys that is composed of additional lists.
So far I have this code:
for i in range(len(keyList)):
if keyList[i] in theInventory:
value = theInventory[keyList[i]]
value.append(valueList[i])
theInventory[keyList[i]] = value
else:
theInventory[keyList[i]] = valueList[i]
The problem is that the output has a list of entries for the first added to the list then it has the lists I am looking to add to my dictionary.
Like so:
[value, value, value, [list], [list]]
How do I make the first entry be entered into the dictionary as its own list?
Use extra [] around valueList[i]:
theInventory[keyList[i]] = [valueList[i]]
You can simplify your code as follows. The append() method mutates the list, so there is no need to assign the result of the append back the theInventory. Further there is no need to use value at all, instead you can just directly append to the item in the dictionary.
for i in range(len(keyList)):
if keyList[i] in theInventory:
theInventory[keyList[i]].append(valueList[i])
else:
theInventory[keyList[i]] = [valueList[i]]
I have a list of several thousand unordered tuples that are of the format
(mainValue, (value, value, value, value))
Given a main value (which may or may not be present), is there a 'nice' way, other than iterating through every item looking and incrementing a value, where I can produce a list of indexes of tuples that match like this:
index = 0;
for destEntry in destList:
if destEntry[0] == sourceMatch:
destMatches.append(index)
index = index + 1
So I can compare the sub values against another set, and remove the best match from the list if necessary.
This works fine, but just seems like python would have a better way!
Edit:
As per the question, when writing the original question, I realised that I could use a dictionary instead of the first value (in fact this list is within another dictionary), but after removing the question, I still wanted to know how to do it as a tuple.
With list comprehension your for loop can be reduced to this expression:
destMatches = [i for i,destEntry in enumerate(destList) if destEntry[0] == sourceMatch]
You can also use filter()1 built in function to filter your data:
destMatches = filter(lambda destEntry:destEntry[0] == sourceMatch, destList)
1: In Python 3 filter is a class and returns a filter object.