Generating random numbers as the value of dictionary in python - python

Could you please tell me how can I generate a dictionary with 100 rows that have random number between 0 and 1 in each row as the value? For example in data frame, I can have:
df['Rand'] = random.sample(random.random(), 100)
But I don't know how to do that for a dictionary.

I think what you want is something like:
{k: random.random() for k in range(100)}

Firstly, it should be list and not dict. Check: In Python, when to use a Dictionary, List or Set?
In order to get the list of values, you may use list comprehension as:
>>> import random
>>> row_count = 10
>>> my_list = [random.random() for i in range(row_count)]
# Value of 'my_list':
# [0.9158936600374181, 0.8998648755500501, 0.07002867165493243, 0.6694284854833131, 0.4903966580363698, 0.9462143737260301, 0.8014661448602305, 0.47964245438139297, 0.42326131297319725, 0.77540761767324]
In order to fetch 5th item (i.e. 4th index):
>>> my_list[4]
0.4903966580363698

Related

Python append to list of lists

I'm trying to simply append to a list of lists but cannot find a clean example of how to do that. I've looked at dozens of examples but they are all for appending to a one-dimensional list or extending lists.
Sample code:
testList = []
print(testList)
testList.append(3000)
print(testList)
testList[3000].append(1)
testList[3000].append(2)
print(testList)
Expected result:
testList[3000][1, 2]
Actual result:
[]
[3000]
Traceback (most recent call last):
File ".\test.py", line 5, in <module>
testList[3000].append(1)
IndexError: list index out of range
The first problem I see is that when you call testList.append() you are including the [3000]. That is problematic because with a list, that syntax means you're looking for the element at index 3000 within testList. All you need to do is call testList.append(<thing_to_append>) to append an item to testList.
The other problem is that you're expecting [1, 2] to be a separate list, but instead you're appending them each to testList.
If you want testList to be composed of multiple lists, a good starting point would be to instantiate them individually, and to subsequently append to testList. This should help you conceptualize the nested structure you're looking for.
For example:
testList = []
three_k = [3000]
one_two = [1, 2]
testList.append(three_k)
testList.append(one_two)
print(testList)
From there, the you can actually use the indexes of the nested lists to append to them. So if [3000] is the list at index 0 (zero), you can append to it by doing: testList[0].append(<new_append_thing>).
First, thank you to everyone for the quick responses. Several of you got me thinking in the right direction but my original question wasn't complete (apologies) so I'm adding more context here that's hopefully helpful for someone else in the future.
wp-overwatch.com jogged my memory and I realized that after working with only dictionaries in my application for days, I was treating the "3000" like a dictionary key instead of the list index. ("3000" is an example of an ID number that I have to use to track one of the lists of numbers.)
I couldn't use a dictionary, however, because I need to add new entries, remove the first entry, and calculate average for the numbers I'm working with. The answer was to create a dictionary of lists.
Example test code I used:
testDict = {}
blah10 = 10
blah20 = 20
blah30 = 30
blah40 = 40
exampleId = 3000
if exampleId == 3000:
testDict[3000] = []
testDict[3000].append(blah10)
testDict[3000].append(blah20)
print(testDict)
testDict[3000].pop(0) # Remove first entry
print(testDict)
testDict[3000].append(blah30) # Add new number to the list
average = sum(testDict[3000]) / len(testDict[3000])
print(average)
if exampleId == 3001:
testDict[3001].append(blah30)
testDict[3001].append(blah40)
Result:
{3000: [10, 20]}
{3000: [20]}
25.0
testList[3000].append(1) is telling Python to grab the 3000th item in the list and call the append function on it. Since you don't have 3000 items in the list, that's why you're getting that error.
If you want to lookup an item by a value such as 3000 instead of by its position in the list, then what you're wanting is not a list but a dictionary.
Using a dictionary you can do:
>>> testList = {} # use curly brackets for a dictionary
>>> print(testList)
{}
>>> testList[3000] = [] # create a new item with the lookup key of 3000 and set the corresponding value to an empty list
>>> print(testList)
{3000: []}
>>> testList[3000].append(1)
>>> testList[3000].append(2)
>>> print(testList)
{3000: [1, 2]}
>>>
It is because according to your program the python interpreter will look for the 3000 index at the list and try to append the given number in the index of 3000 but there is not that number so it will print error.
To fix it:
testList = []
print(testList)
testList.append(3000)
print(testList)
testList.append([1])
testList[1].append(2)
print(testList)
Using the index you can append the value as I appended.
list.append adds an object to the end of a list. So doing,
listA = []
listA.append(1)
now listA will have only the object 1 like [1].
you can construct a bigger list doing the following
listA = [1]*3000
which will give you a list of 3000 times 1 [1,1,1,1,1,...].
If you want to contract a c-like array you should do the following
listA = [[1]*3000 for _ in range(3000)]
Now you have a list of lists like [[1,1,1,1,....], [1,1,1,....], .... ]
PS Be very careful using [1]*3000 which in this case works
but in case you use it with a variable it will have side effects. For example,
a = 1
listA = [a]*3000
gives you the same result but if any of the variables 'a' change then all will be changed the same way.
The most safe is, using list comprehensions
a = 1
listA = [a for _ in range(3000)]
In order to update any value, just do the following,
listA[656] = 999
Lastly, in order to extend the above list just type
listA.append(999)
and then at the index 3000 (starting from zero) you will find 999

Check most common occurrence of a value of one list in a separate list

I have a list of numbers.
somelist = [5.000007,5.00099,5.0000075,5.0000075,5.0000075,5.0000099,5.00099,5.0000080,5.0000081,5.00099,5.0000080,5.0000096,5.0000087,5.008,5.00099,5.00000009]
I’m using the following to produce a unique list of the 3 lowest values:
def lowest_three(somelist):
lowest_unique = set(somelist)
return nsmallest(3, lowest_unique)
It produces the output:
[5.00000009, 5.000007, 5.0000075]
Now I want a separate function to tell me which of the three lowest values is the most commonly occuring in the original list.
So I want it to tell me that 5.0000075 is the most common number from the lowest_three list in the original list (somelist).
I’ve tried the following but it’s not working (it’s currently producing an output of 5.00099 which isn’t even in the lowest_three list).
def most_common_lowest(somelist):
for x in lowest_three(somelist):
return max(set(somelist), key=somelist.count)
How can achieve this?
Now I want a separate function to tell me which of the three lowest values is the most commonly occuring in the original list.
def most_common_lowest(somelist):
for x in lowest_three(somelist):
return max(set(somelist), key=somelist.count)
That code doesn't make sense. Should be:
def most_common_lowest(somelist):
return max(lowest_three(somelist), key=somelist.count)
You could possibly collect the counts with collections.Counter(), with only values from somelist that exist in top_three, then take the most_common of this:
from heapq import nsmallest
from collections import Counter
somelist = [5.000007,5.00099,5.0000075,5.0000075,5.0000075,5.0000099,5.00099,5.0000080,5.0000081,5.00099,5.0000080,5.0000096,5.0000087,5.008,5.00099,5.00000009]
def lowest_three(somelist):
lowest_unique = set(somelist)
return nsmallest(3, lowest_unique)
top_three = lowest_three(somelist)
# [5.00000009, 5.000007, 5.0000075]
freqs = Counter(x for x in somelist if x in top_three)
# Counter({5.0000075: 3, 5.000007: 1, 5.00000009: 1})
print(freqs.most_common(1)[0][0])
# 5.0000075
O you could group them in a collections.defaultdict, and take the max manually:
from collections import defaultdict
from operator import itemgetter
filtered_values = [x for x in somelist if x in top_three]
# [5.000007, 5.0000075, 5.0000075, 5.0000075, 5.00000009]
freqs = defaultdict(int)
for val in filtered_values:
freqs[val] += 1
# defaultdict(<class 'int'>, {5.000007: 1, 5.0000075: 3, 5.00000009: 1})
print(max(freqs.items(), key = itemgetter(1))[0]) # or key = lambda x: x[1]
# 5.0000075
Given the returned list from lowest_three, you can use list.count:
somelist = [5.000007,5.00099,5.0000075,5.0000075,5.0000075,5.0000099,5.00099,5.0000080,5.0000081,5.00099,5.0000080,5.0000096,5.0000087,5.008,5.00099,5.00000009]
new_list = lowest_three(somelist)
final_data = sorted(new_list, key=lambda x:somelist.count(x))[-1]
Output:
5.0000075
One option is to use collections.Counter.
from collections import Counter
counts = Counter(somelist)
lowest = lowest_three(somelist)
for num in lowest:
print counts[num]
// i think you better write an algorithm for this operation your self (for the practice)
a simple algorithm :
create a map contining only those 3 elements ,(witch you already found), as keys, and 0 as value.
run over the array and for each element in the array chack if the map contains him, if it does inc the value by 1 (map[key] = map[key]+1) .
iterate over your map and find the key with the highest value.
(it's like a counters array but with map data structure)
Use Counter from collections module and use sorted function, twice once for getting the 3 minimum elements and and second time for getting maximum occurring element
from collections import Counter
somelist = [5.000007,5.00099,5.0000075,5.0000075,5.0000075,5.0000099,5.00099,5.0000080,5.0000081,5.00099,5.0000080,5.0000096,5.0000087,5.008,5.00099,5.00000009]
lowest_three=sorted(Counter(somelist).items(), key=lambda i: i[0])[:3]
print(sorted(lowest_three,key=lambda i :-i[1])[0])
OUTPUT
(5.0000075, 3)
You can use the function min. It might solve your problem out.
#!/usr/bin/python
var list = [5.00000009, 5.000007, 5.0000075]
print "min value element : ", min(list)
https://www.tutorialspoint.com/python/list_min.htm
Everyone suggesting you collection module , You can do without collection and in few lines , Here you go:
somelist = [5.000007,5.00099,5.0000075,5.0000075,5.0000075,5.0000099,5.00099,5.0000080,5.0000081,5.00099,5.0000080,5.0000096,5.0000087,5.008,5.00099,5.00000009]
values=[5.00000009, 5.000007, 5.0000075]
track={}
for j,i in enumerate(somelist):
if i in values:
if i not in track:
track[i]=1
else:
track[i]+=1
print(max(list(map(lambda x:(track[x],x),track))))
output:
(3, 5.0000075)

Print both the duplicate values name from the nested list

students=[['Ash',85.25],['Kai',85.25],['Ray',75],['Jay',55.5]]
output:Ash
Kai
I'm trying to solve a task and i'm new in python.I am not getting what i want can anyone explain me how one can do it
One option would be to group the values into a defaultdict(list):
>>> from collections import defaultdict
>>>
>>> students = [['Ash',85.25],['Kai',85.25],['Ray',75],['Jay',55.5]]
>>> d = defaultdict(list)
>>> for value, key in students:
... d[key].append(value)
...
>>> for value in d.itervalues():
... if len(value) > 1:
... print(value)
...
['Ash', 'Kai']
I would do it like that:
students = [['Ash', 85.25], ['Kai', 85.25], ['Ray', 75], ['Jay', 55.5]]
common_names = []
for i, i_x in enumerate(students):
for i_y in students[:i] + students[i + 1:]:
if i_x[1] == i_y[1]:
common_names.append(i_x[0])
print(common_names)
#['Ash', 'Kai']
# or if you want it to print every entry in a single line:
print('\n'.join(x for x in common_names))
#Ash
#kai
Explain:
I grab an object from the original list students. Object is i_x and its ['Ash', 85.25] on the first iteration for example.
Then i slice the list students[:i] + students[i + 1:] to create another one in memory that contains all the elements of the original one apart from i_x
I check to see if there is any item in the newly created list that has the same [1] index value as that of i_x. If yes, i append the i_x[0] value to a third list that holds the results.
I do this for as many elements as there are originally in the students list.
Can anybody provide a list comprehension for the above?

Extracting keys-values from dictionary

import random
dictionary = {'dog': 1,'cat': 2,'animal': 3,'horse': 4}
keys = random.shuffle(list(dictionary.keys())*3)
values = list(dictionary.values())*3
random_key = []
random_key_value = []
random_key.append(keys.pop())
random_key_value.append(???)
For random_key_values.append, I need to add the value that corresponds to the key that was popped. How can I achieve this? I need to make use of multiples of the list and I can't multiply a dictionary directly, either.
I'm going on python (you should specify the language in your question).
If I understand, you want to multiply the elements in the dictionary. So
list(dictionary.keys()) * 3
is not your solution: [1,2] * 3 results in [1,2,1,2,1,2]
Try instead list comprehension:
[i * 3 for i in dictionary.keys()]
To take into account the order (because you shuffle it) shuffle the keys before the multiplication, then create the values list (in the same order that the shuffled keys) and finally multiply the keys:
keys = dictionary.keys()
random.shuffle(keys)
values = [dictionary[i]*3 for i in keys]
keys = [i * 3 for i in keys]
And finally:
random_key.append(keys.pop())
random_key_value.append(values.pop())
Also take care about the random function, it doesn't work as you are using it. See the documentation.

How do I index a dictionary of multiple lists using a list of indexes?

I'm on Python 2.7.3.
If I have a dictionary of lists, like this:
>>> x1 = [1,2,3,4,5,6,7,8,5]
>>> x2 = range(11,20)
>>> mydict = {'first':x1,'second':x2}
... and the lists are equal size...
>>> len(mydict['second']) == len(mydict['first'])
True
How do I use a list of indexes like this:
>>> ind = [0,1,2,3,4,5,6,7]
To get the values from both lists in my dictionary? I have tried to use the "ind" list to index, but continuously get an error whether ind is a list or tuple like this:
>>> mydict['second'][ind]
TypeError: list indices must be integers, not set
I realize that the list isn't an integer, but each value in the set is an integer. Is there any way to get to the x1[ind] and x2[ind ] without iterating a counter" in a loop?
Don't know if it matters, but I have the index list already that I got from finding the unique values like this:
>>> import numpy as np
>>> ux1 = np.unique(x1, return_index = True)
You can use operator.itemgetter:
from operator import itemgetter
indexgetter = itemgetter(*ind)
indexed1 = indexgetter(mydict['first'])
indexed2 = indexgetter(mydict['second'])
note that in my example, indexed1 and indexed2 will be tuple instances, not list
instances. The alternative is to use a list comprehension:
second = mydict['second']
indexed2 = [second[i] for i in ind]
You want to use operator.itemgetter:
getter = itemgetter(*ind)
getter(mydict['second']) # returns a tuple of the elements you're searching for.

Categories

Resources