Searching for elements in a python list - python

Searching for elements in a python list and then accessing particular values
Mylist = [('A',3,['x','y','z']),('B',2,['m','n'])]
Variable = 'A'
i = Mylist.index(Variable)
print i
For example I would like to check if is Variable is present and access its elements like
is present then access each of sublist elements one by one
For instance in the above example I would like to check if 'A' is present and if yes then
get access to its individual sublist elements like 'x' , 'y' and 'z'

It looks like you haven't found the Python dict yet. Perhaps you mean:
mydict = {}
mydict['A'] = {'count': 3, 'letters': ['x','y','z']}
mydict['B'] = {'count': 2, 'letters': ['m','n']}
mydict is a dictionary that itself contains dictionaries.
You can then look them up with:
val = mydict['A']
print val['letters']
Of course, there's little point in storing 'count' since you can just use len() if you need to. You could do it like so:
mydict = {'A': ['x','y','z'], 'B': ['m','n']}
print mydict['A']

You just need to use a dictionary...
myDict = dict([('A',3,['x','y','z']),('B',2,['m','n'])])
if 'A' in myDict:
val = myDict['A']

As others have said, a dict is really the appropriate data type to use when you need to index things by arbitrary data types (like strings). With nested sequences, there's no guarantee that your 'index' (the 'A' and 'B' in this case) will be unique, and some extra contortion is needed to look up values. Also as others have said, the ['x', 'y', 'z'] part will remain in order, regardless of whether it's a list-in-a-tuple-in-a-list, or a list-in-a-dict.
That said, the easiest way I can think of to find the tuple you want without using a dict is:
indices = zip(*Mylist)[0] # ('A', 'B')
index = indices.index('A') # 0
result = Mylist[index] # ('A', 3, ['x', 'y', 'z'])
To get at the sublist, use its index:
sublist = result[2]
or unpack it:
lookup, length, sublist = result

Mylist = [('A',3,['x','y','z']),('B',2,['m','n']),
('C',5,['r','p','u']),('A',10,['k','X']),
('E',8,['f','g','h','j'])]
for i,(a,b,c) in enumerate(Mylist):
if a=='A':
print i,c
result
0 ['x', 'y', 'z']
3 ['k', 'X']

Related

How to sort and export all overlap key of value on dictionary of python?

For example, my dictionary contain this:
a = {1:'a',3:'b',2:'c',4:'d',1:'e',4:'f'}
To sort key on that list, I can do this:
b = []
for m in a:
b.append(m)
b.sort()
for value in b:
print(a[value])
The problem is: 'd' and 'e' share the same value 4, and its only export one value. But I want to export all of them. How can I do that?
A dictionary is assigns a value to a key (or a key references a specific value). Therefore it is not possible to have a dictionary with the same key twice (check, what a looks like after assigning!).
What you may want to look at is a list of tuples!
a = [(1,'a'),(3,'b'),(2,'c'),(4,'d'),(1,'e'),(4,'f')]
After that, you can do the sorting just by doing this:
a.sort(key=lambda x: x[0])
Duplicate keys in a dictionary is not allowed. Your dict does not contain what you think.
>>> a = {1:'a',3:'b',2:'c',4:'d',1:'e',4:'f'}
>>> a
{1: 'e', 2: 'c', 3: 'b', 4: 'f'}
When initializing your dictionary, the key 4 is defined twice: 4:'d', 4:'f'.
The second value 'f' overwrites the 'd' stored at a[4]. This is by design and therefore, you would need to correct your implementation to take this behaviour into account.

Python searching a Json with key value

I'm having a JSON file and I'm trying to do a search using the values ( not the keys). Is there a built in function in Python that does so?
[["2778074170846781111111110", "a33104eb1987bec2519fe051d1e7bd0b4c9e4875"],
["2778074170846781111111111", "f307fb3db3380bfd27901bc591eb025398b0db66"]]
I thought of this approach. Loading the file into a list and start searching. Is there a more efficient way?
def OptionLookUp(keyvalue):
with open('data.json', 'r') as table:
x= json.loads(table)
After your edit I can say that there is no faster/more efficient way than turning your JSON into python 2-dimensional list and loop through each node and compare second field with your "keyvalue".
EDIT: faster/more efficient
your_dict = {'a': 1, 'b': 2, 'c': 'asd'} # the dictionary
your_value = 'asd' # the value to look for
[elem for elem in your_dict.iteritems() if elem[1] == 'asd'] # look for entry with value == your_value
Output: [('c', 'asd')]
EDIT:
for a list:
your_list = [['a', 1], ['b', 2], ['c', 'asd']] # the list
your_value = 'asd' # the value to look for
[elem for elem in your_list if elem[1] == 'asd'] # look for element with value == your_value
Output: [('c', 'asd')]
I assume you're looking for the key (or keys) associated with a given value.
If your data is garanteed to be a list of (key, value) pairs, depending on 1/ the data's volume and 2/ how many lookups you'll have to perform on a same dataset, you can either do a plain sequential search:
def slookup(lst, value):
return [k for k, v in lst if v == value]
or build a reverse index then lookup the index:
import defaultdict
def index(lst):
d = defaultdict(list)
for k, v in lst:
d[v].append(k)
return d
rindex = index(lst)
print rindex.get(someval)
print rindex.get(someotherval)
This second solution only makes sense if you have a lot of lookups to do on the same dataset, obviously...

How to remove a dict objects(letter) that remain in another str?

Suppose I have this dictionary:
x = {'a':2, 'b':5, 'g':7, 'a':3, 'h':8}`
And this input string:
y = 'agb'
I want to delete the keys of x that appear in y, such as, if my input is as above, output should be:
{'h':8, 'a':3}
My current code is here:
def x_remove(x,word):
x1 = x.copy() # copy the input dict
for i in word: # iterate all the letters in str
if i in x1.keys():
del x1[i]
return x1
But when the code runs, it removes all existing key similar as letters in word. But i want though there is many keys similar as letter in word , it only delete one key not every
wheres my wrong, i got that maybe but Just explain me how can i do that without using del function
You're close, but try this instead:
def x_remove(input_dict, word):
output_dict = input_dict.copy()
for letter in word:
if letter in output_dict:
del output_dict[letter]
return output_dict
For example:
In [10]: x_remove({'a': 1, 'b': 2, 'c':3}, 'ac')
Out[10]: {'b': 2}
One problem was your indentation. Indentation matters in Python, and is used the way { and } and ; are in other languages. Another is the way you were checking to see if each letter was in the list; you want if letter in output_dict since in on a dict() searches keys.
It's also easier to see what's going on when you use descriptive variable names.
We can also skip the del entirely and make this more Pythonic, using a dict comprehension:
def x_remove(input_dict, word):
return {key: value for key, value in input_dict if key not in word}
This will still implicitly create a shallow copy of the list (without the removed elements) and return it. This will be more performant as well.
As stated in the comments, all keys in dictionaries are unique. There can only ever be one key named 'a' or b.
Dictionary must have unique keys. You may use list of tuples for your data instead.
x = [('a',2), ('b',5), ('g',7), ('a',3), ('h',8)]
Following code then deletes the desired entries:
for letter in y:
idx = 0
for item in x.copy():
if item[0] == letter:
del x[idx]
break
idx += 1
Result:
>>> x
[('a', 3), ('h', 8)]
You can also implement like
def remove_(x,y)
for i in y:
try:
del x[i]
except:
pass
return x
Inputs x = {'a': 1, 'b': 2, 'c':3} and y = 'ac'.
Output
{'b': 2}

Update values for multiple keys in python

What is the cleanest way to update the values of multiple keys in a dictionary to the values stored in a tuple?
Example:
I want to go from
>>>mydict = {'a':None, 'b':None, 'c':None, 'd':None}
>>>mytuple = ('alpha', 'beta', 'delta')
to
>>>print mydict
{'a':'alpha', 'b':'beta', 'c':None, 'd':'delta'}
Is there an easy one-liner for this? Something like this seems to be getting close to what I want.
EDIT:
I don't wish to assign values to keys based on their first letter. I'm just hoping for something like
mydict('a','b','d') = mytuple
Obviously that doesn't work, but I'm hoping for something similar to that.
If you're trying to create a new dictionary:
d = dict(zip(keys, valuetuple))
If you're trying to add to an existing one, just change the = to .update(…).
So, your example can be written as:
mydict.update(dict(zip('abd', mytuple))))
If you're doing this more than once, I'd wrap it up in a function, so you can write:
setitems(d, ('a', 'b', 'd'), mytuple)
Or maybe a "curried" function that parallels operator.itemgetter?
You could use list comprehension to make it a one-liner, though it's not super efficient.
keys = [ 'a', 'b', 'c', 'd']
values = ['alpha', 'beta', 'delta']
dictionary = dict([(k,v) for k in keys for v in values if v.startswith(k)])
print dictionary #prints {'a': 'alpha', 'b': 'beta', 'd': 'delta'}
Assuming the association key <-> value is the first letter of the value is the first letter of the key.
dict( (v[0],v) for v in mytuple if v[0] in mydict)
I would avoid one-liners in this case. It makes code more readable.
for t in mytuple:
if t[0] in mydict.keys():
mydict[t[0]] = t
If you want to add mytuple items even if the key does not exist, simply remove the if statement.

Converting Dictionary to List? [duplicate]

This question already has answers here:
How can I convert a dictionary into a list of tuples?
(13 answers)
Closed 3 years ago.
I'm trying to convert a Python dictionary into a Python list, in order to perform some calculations.
#My dictionary
dict = {}
dict['Capital']="London"
dict['Food']="Fish&Chips"
dict['2012']="Olympics"
#lists
temp = []
dictList = []
#My attempt:
for key, value in dict.iteritems():
aKey = key
aValue = value
temp.append(aKey)
temp.append(aValue)
dictList.append(temp)
aKey = ""
aValue = ""
That's my attempt at it... but I can't work out what's wrong?
dict.items()
Does the trick.
Converting from dict to list is made easy in Python. Three examples:
>> d = {'a': 'Arthur', 'b': 'Belling'}
>> d.items()
[('a', 'Arthur'), ('b', 'Belling')]
>> d.keys()
['a', 'b']
>> d.values()
['Arthur', 'Belling']
Your problem is that you have key and value in quotes making them strings, i.e. you're setting aKey to contain the string "key" and not the value of the variable key. Also, you're not clearing out the temp list, so you're adding to it each time, instead of just having two items in it.
To fix your code, try something like:
for key, value in dict.iteritems():
temp = [key,value]
dictlist.append(temp)
You don't need to copy the loop variables key and value into another variable before using them so I dropped them out. Similarly, you don't need to use append to build up a list, you can just specify it between square brackets as shown above. And we could have done dictlist.append([key,value]) if we wanted to be as brief as possible.
Or just use dict.items() as has been suggested.
You should use dict.items().
Here is a one liner solution for your problem:
[(k,v) for k,v in dict.items()]
and result:
[('Food', 'Fish&Chips'), ('2012', 'Olympics'), ('Capital', 'London')]
or you can do
l=[]
[l.extend([k,v]) for k,v in dict.items()]
for:
['Food', 'Fish&Chips', '2012', 'Olympics', 'Capital', 'London']
>>> a = {'foo': 'bar', 'baz': 'quux', 'hello': 'world'}
>>> list(reduce(lambda x, y: x + y, a.items()))
['foo', 'bar', 'baz', 'quux', 'hello', 'world']
To explain: a.items() returns a list of tuples. Adding two tuples together makes one tuple containing all elements. Thus the reduction creates one tuple containing all keys and values and then the list(...) makes a list from that.
Probably you just want this:
dictList = dict.items()
Your approach has two problems. For one you use key and value in quotes, which are strings with the letters "key" and "value", not related to the variables of that names. Also you keep adding elements to the "temporary" list and never get rid of old elements that are already in it from previous iterations. Make sure you have a new and empty temp list in each iteration and use the key and value variables:
for key, value in dict.iteritems():
temp = []
aKey = key
aValue = value
temp.append(aKey)
temp.append(aValue)
dictList.append(temp)
Also note that this could be written shorter without the temporary variables (and in Python 3 with items() instead of iteritems()):
for key, value in dict.items():
dictList.append([key, value])
If you're making a dictionary only to make a list of tuples, as creating dicts like you are may be a pain, you might look into using zip()
Its especialy useful if you've got one heading, and multiple rows. For instance if I assume that you want Olympics stats for countries:
headers = ['Capital', 'Food', 'Year']
countries = [
['London', 'Fish & Chips', '2012'],
['Beijing', 'Noodles', '2008'],
]
for olympics in countries:
print zip(headers, olympics)
gives
[('Capital', 'London'), ('Food', 'Fish & Chips'), ('Year', '2012')]
[('Capital', 'Beijing'), ('Food', 'Noodles'), ('Year', '2008')]
Don't know if thats the end goal, and my be off topic, but it could be something to keep in mind.

Categories