Access array based on number of named key - python

json_data = {"fruits": ["apple", "banana", "orange"],"vegetables":["tomatoe", "cucumber", "potato"]}
How do I access my array numerically without having to include a numeric key?
ex:
json_data[0][0] #result should equal "apple"

You can't. The outer container is an unordered dictionary, not a list, so an index of 0 is meaningless. If you have some way of ordering the keys, you could then use the dict.keys() function to build a list and index that. The problem is, that keys() can come up in any order, so you'd still need some other ordering principle.

json_data[list(json_data.keys())[0]][0]
this is how to do it, but it is extremely wrong, ugly and unpythonic, and you should probably be looking for another way to do this.
starting from the inside json_data.keys() returns all the keys
list() turns those keys into a list [0] after it, accesses the zeroth item in the list
json_data[] around that accesses the list by key
[0] after it accesses the zeroth item in the returned list
Also it is not guaranteed to work 100% of the time, because json_data.keys() is not guaranteed to always output at the same order.

Related

Python: Randomly Select One Key From All Keys in a Dictionary

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]).

Python Matching Multiple Keys/ Unique Pairs to a Value

What would be the fastest, most efficient way to grab and map multiple values to one value. For a use case example, say you are multiplying two numbers and you want to remember if you have multiplied those numbers before. Instead of making a giant matrix of X by Y and filling it out, it would be nice to query a Dict to see if dict[2,3] = 6 or dict[3,2] = 6. This would be especially useful for more than 2 values.
I have seen an answer similar to what I'm asking here, but would this be O(n) time or O(1)?
print value for matching multiple key
for key in responses:
if user_message in key:
print(responses[key])
Thanks!
Seems like the easiest way to do this is to sort the values before putting them in the dict. Then sort the x,y... values before looking them up. And note that you need to use tuples to map into a dictionary (lists are mutable).
the_dict = {(2,3,4): 24, (4,5,6): 120}
nums = tuple(sorted([6,4,5]))
if nums in the_dict:
print(the_dict[nums])

Assign list values to dictionary keys

So I want to loop over a dictionary and a list simultaneously without them being nested.
What I really mean is:
for i,c in enumerate(dictionary) and for k in range(len(list)):
dictionary[c] = list[k]
So it basically loops over one dictionary and I can assign values to the dictionary with a list.
IIUC, you are trying to reassign existing keys to list values. This is something you can only do from python-3.7 onwards (or 3.6 if you use CPython). This can be done either through direct reassignment,
dictionary = dict(zip(dictionary, lst))
Or, if they are not the same length, and there are keys you want to preserve, use dict.update:
dictionary.update(dict(zip(dictionary, lst)))
Additionally, it is unwise to name variables after builtin objects (such as list).
zip is your friend
dictionary.update(zip(dictionary, lst))

Using defaultdict in python

I am reading items from a txt file into a list and then converting it into a dictionary as follows-
def getfeatures_into_list(inputfilename):
fid=open(inputfilename,"r")
dict_Lab_Features=defaultdict(int)
list1=[]
for line in fid:
list1.append(line.rstrip().lower())
list1=list(set(list1)) #Removing duplicates
c=0
for items in sorted(list1):
dict_Lab_Features[items]=c
c+=1
dict_Lab_Features=sorted(dict_Lab_Features.items(), key=operator.itemgetter(1))
print(dict_Lab_Features['Hello'])
I am getting error in the print statement
list indices must be integer,not str
Edit I want to sort the dict by value in ascending order.
In this line:
dict_Lab_Features=sorted(dict_Lab_Features.items(), key=operator.itemgetter(1))
you have reassigned dict_Lab_Features so that it is a list. This is because the output of sorted() is always a list. Naturally, a list cannot take a string as an index.
You should learn to think of dictionaries as inherently unsorted. There is such a thing as an OrderedDict for when you really need to keep track of insertion order, but for most purposes, a regular dict is fine. You just have to get into the habit of traversing the dictionary in the desired order, not worrying about whether the dictionary is stored in any kind of order.
The usual way to traverse a dictionary in sorted order is to just loop over the sorted keys, such as:
for key in sorted(dict_Lab_Features):
print dict_Lab_Features[key]
or
for key, value in sorted(dict_Lab_Features.items()):
print value
Or, if you want to loop over the sorted values,
for value in sorted(dict_Lab_Features.values()):
print value
You cannot sort a dict. Dicts are unordered mappings of elements.
Let's analyize the following line:
dict_Lab_Features=sorted(dict_Lab_Features.items(), key=operator.itemgetter(1))
From the documentation of sorted:
Return a new sorted list from the items in iterable.
So after that, dict_Lab_Features is a sorted list of key-value tuples. After that you try to index it with 'Hello'
print(dict_Lab_Features['Hello'])
Here you try to index that list with 'Hello', that's why you get the error list indices must be integer,not str
dict_Lab_Features stops being a dict when you call dict.items(). A dict.items() object cannot be addressed using string keys (it's really just a list of tuples [(key, value), ... ]).
Furthermore, "sorting" a dictionary you then intend to use by name doesn't make much sense either. Looks like you either need a collections.OrderedDict or you should skip ordering altogether

finding first item in a list whose first item in a tuple is matched

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.

Categories

Resources