help sorting a dictionary into another dictionary - python

I have a dictionary (index2) of 3-item lists, organized by key from 0-150 or so. I need to sort it into another dictionary, with the following constraints:
1.) all items attached to one key must stay together in the second dictionary
2.) length of items in the second dictionary must all be the same. To help with this one, I divided the total number of items in the first dictionary by the number of keys in the second and attached it to a variable so it can be used as a limiting factor.
This is what I have so far, however when I run it, it doesn't actually append anything to the target dictionary.
for key,runs in index2.iteritems():
for a in mCESrange:
if index2[key][0] in mCESdict[a]:
pass
elif len(mCESdict[a]) < mCESlength:
pass
else:
mCESdict[a].extend(index2[key])

Your problem description isn't really clear, and non-working code rarely helps to clarify, but I suspect that this line is your problem: elif len(dict[a]) < length.

Related

Ignoring a key when looping through a sorted dictionary in Python

I have a dictionary in python and I'm assigning elements to an array utilizing a key with four elements. I want to plot my arrays by looping through my sorted dictionary but I'd like to ignore one of the keys in the loop. My code looks like this:
key = (process, temp, board, chip)
#Do some stuff in a loop
for key in sorted(svmDict):
#plot some things but don't sort with the variable chip
I found some articles for removing a specific key but in my case chip is actually a variable and I removing each key seems cumbersome and likely unnecessary.
If you're not worried about speed I would just check whether or not you are at an acceptable key in the loop. You can directly check against one value you want to skip or make a list of values you want to skip
ignore_list = [chip]
for key in sorted(svmDict):
if key not in ignore_list:
#do the thing

Assign a Range of Numbers to a Single Key with Dictionaries

I was working on a dictionary, but I came up with an issue. And the issue is, I want to be able to use more than 1 number in order to reference a key in a dictionary.
For example, I want the range of numbers between 1 and 5 to be all assigned to, let's say, "apple". So I came up with this:
my_dict['apple'] = range(1,5)
At the program's current state, its far from being able to run, so testing is an issue, but I do not receive any issues from my editor. I was just wondering, is this the correct way to go about this? Or is there a better way?
Thanks.
EDIT:
A little more info: I want to make a random integer with the randint function. Then, after Python has generated that number, I want to use it to call for the key assigned to the value of the random integer. Thing is, I want to make some things more common than others, so I want to make the range of numbers I can call it with larger so the chance of the key coming up becomes likelier. Sorry if it doesn't make much sense, but at the current state, I really don't even have code to show what I'm trying to accomplish.
You have the dictionary backwards. If you want to be able to recall, e.g., 'apple' with any of the numbers 1-5, you'd need the numbers to be the keys, not the values.
for i in range(1,6): # range(a,b) gives [a,b)
my_dict[i] = 'apple'
etc. Then, my_dict[4] == 'apple' and the same is true for the other values in the range.
This can create very large dictionaries with many copies of the same value.
Alternately, you can use range objects as dictionary keys, but the testing will be a bit more cumbersome unless you create your own class.
my_dict[range(1,6)] = 'apple'
n = random.randint(1, 5)
for key in my_dict:
if n in key:
print(my_dict[key])
...prints apple.
The value in a dictionary can be any arbitrary object. Whether it makes sense to use a given type or structure as a value only makes sense in the context of the complete script, so it is impossible to tell you whether it is the correct solution with the given information.

Sorting based on a variable number of sort keys input after execution

I am very new to python and my apologies is this has already been answered. I can see a lot of previous answers to 'sort' questions but my problem seems a little different from these questions and answers.
I have a list of keys, with each key contained in a tuple, that I am trying to sort. Each key is derived from a subset of the columns in a CSV file, but this subset is determined by the user at runtime and can't be hard coded as it will vary from execution to execution. I also have a datetime value that will always form part of the key as the last item in the tuple (so there will be at least one item to sort on - even if the user provides no additional items).
The tuples to be sorted look like:
(col0, col1, .... colN, datetime)
Where col0 to colN are based on the values found in columns in a CSV file, and the 'N' can change from run to run.
In each execution, the tuples in the list will always have the same number of items in each tuple. However, they need to be able to vary from run to run based on user input.
The sort looks like:
sorted(concurrencydict.keys(), key=itemgetter(0, 1, 2))
... when I do hard-code the sort based on the first three columns. The issue is that I don't know in advance of execution that 3 items will need to be sorted - it may be 1, 2, 3 or more.
I hope this description makes sense.
I haven't been able to think of how I can get itemgetter to accept a variable number of values.
Does anyone know whether there is an elegant way of performing a sort based on a variable number of items in python where the number of sort items is determined at run time (and not based on fixed column numbers or attribute names)?
I guess I'll turn my comment into an answer.
You can pass a variable number of arguments (which are packed into an iterable object) by using *args in the function call. In your specific case, you can put your user-supplied selection of column numbers to sort by into a sort_columns list or tuple, then call:
sorted_keys = sorted(concurrencydict.keys(), key=itemgetter(*sort_columns))

Error in selecting random item from Dictionary in python

I wan't to create a program that select 2 random items from two different dictionaries. Now I wan't to check if the sum of those items is equal to the value provided by the User. And i wan't to perform this action until i find 2 random items from different dictionaries that add up to the number entered by the User.
Here is what i tried to do:
import random
credit=int(raw_input("Please enter your amount: "))
food=dict([(10, 'Lays'), (10,'Pepsi'), (10,'Burger')])
toys=dict([(10, 'Car'), (10,'Train'), (10,'Chess')])
ranf=random.choice(food.keys())
rant=random.choice(toys.keys())
while int(ranf)+int(rant)!=credit:
ranf=random.choice(food.keys())
rant=random.choice(toys.keys())
print(ranf)
print(food[ranf])
print(rant)
print(food[rant])
When i try to run this code it fails to print those two random items. I'm not getting any error message. Please run this code and help me out.
Thank You
The problem lies within the fact, that you create your dictionaries with duplicate keys - effectively, your food dictionary contains only (10,'Burger') and your toys dictionary has only (10,'Chess') item (they both contain only most recently added item, which replaced all the previous ones). The simplest and quickest fix would be to abandon the usage of a dictionary:
import random
credit=20
food=[(10, 'Lays'), (10,'Pepsi'), (10,'Burger')]
toys=[(10, 'Car'), (10,'Train'), (10,'Chess')]
ranf=random.choice(food)
rant=random.choice(toys)
while int(ranf[0])+int(rant[0])!=credit:
ranf=random.choice(food)
rant=random.choice(toys)
print(ranf)
print(rant)
food.keys() only returns unique keys. So, essentially the only list of keys returned by the food.keys() function is [10].
ex if you make a dictionary like food = dict([(10, 'Lays'), (15,'Pepsi'), (15,'Burger')])
then the list returned by food.keys() will be [10,15] and not [10,15,15] which is what you expect. So, in your code, if ranf = 10, then interpreter takes up the latest value assigned to that key.
Therefore, the random.choice() you are using goes in vain.
Also, there is a silly mistake in your code, you wrote print(food[rant]) instead of writing print(toys[rant]).
It would be better if you don't use a list, otherwise, make the keys different.

How to rewrite this Dictionary For Loop in Python?

I have a Dictionary of Classes where the classes hold attributes that are lists of strings.
I made this function to find out the max number of items are in one of those lists for a particular person.
def find_max_var_amt(some_person) #pass in a patient id number, get back their max number of variables for a type of variable
max_vars=0
for key, value in patients[some_person].__dict__.items():
challenger=len(value)
if max_vars < challenger:
max_vars= challenger
return max_vars
What I want to do is rewrite it so that I do not have to use the .iteritems() function. This find_max_var_amt function works fine as is, but I am converting my code from using a dictionary to be a database using the dbm module, so typical dictionary functions will no longer work for me even though the syntax for assigning and accessing the key:value pairs will be the same. Thanks for your help!
Since dbm doesn't let you iterate over the values directly, you can iterate over the keys. To do so, you could modify your for loop to look like
for key in patients[some_person].__dict__:
value = patients[some_person].__dict__[key]
# then continue as before
I think a bigger issue, though, will be the fact that dbm only stores strings. So you won't be able to store the list directly in the database; you'll have to store a string representation of it. And that means that when you try to compute the length of the list, it won't be as simple as len(value); you'll have to develop some code to figure out the length of the list based on whatever string representation you use. It could just be as simple as len(the_string.split(',')), just be aware that you have to do it.
By the way, your existing function could be rewritten using a generator, like so:
def find_max_var_amt(some_person):
return max(len(value) for value in patients[some_person].__dict__.itervalues())
and if you did it that way, the change to iterating over keys would look like
def find_max_var_amt(some_person):
dct = patients[some_person].__dict__
return max(len(dct[key]) for key in dct)

Categories

Resources