I have two Arrays:
firstArray=[['AF','AFGHANISTAN'],['AL','ALBANIA'],['DZ','ALGERIA'],['AS','AMERICAN SAMOA']]
secondArray=[[1,'AFGHANISTAN'],[3,'AMERICAN SAMOA']]
So I just need an Array which is like
thirdArray=[[1,'AF'],[3,'AS']]
I tried any(e[1] == firstArray[i][1] for e in secondArray)
It returned me True and false if second element of both array matches. but i don't know how to build the third array.
First, convert firstArray into a dict with the country as the key and abbreviation as the value, then just look up the abbreviation for each country in secondArray using a list comprehension:
abbrevDict = {country: abbrev for abbrev, country in firstArray}
thirdArray = [[key, abbrevDict[country]] for key, country in secondArray]
If you are on a Python version without dict comprehensions (2.6 and below) you can use the following to create abbrevDict:
abbrevDict = dict((country, abbrev) for abbrev, country in firstArray)
Or the more concise but less readable:
abbrevDict = dict(map(reversed, firstArray))
It is better to store them into dictionaries:
firstDictionary = {key:value for value, key in firstArray}
# in older versions of Python:
# firstDictionary = dict((key, value) for value, key in firstArray)
then you could get the 3rd array simply by dictionary look-up:
thirdArray = [[value, firstDictionary[key]] for value, key in secondArray]
You could use an interim dict as a lookup:
firstArray=[['AF','AFGHANISTAN'],['AL','ALBANIA'],['DZ','ALGERIA'],['AS','AMERICAN SAMOA']]
secondArray=[[1,'AFGHANISTAN'],[3,'AMERICAN SAMOA']]
lookup = {snd:fst for fst, snd in firstArray}
thirdArray = [[n, lookup[name]] for n, name in secondArray]
If a dictionary would do, there is a special purpose Counter dictionary for exactly this use case.
>>> from collections import Counter
>>> Counter(firstArray + secondArray)
Counter({['AF','AFGHANISTAN']: 1 ... })
Note that the arguments are reversed from what you requested, but that's easily remedied.
The standard way to match data to a key is a dictionary. You can convert firstArray to a dictionary using dict comprehension.
firstDict = {x: y for (y, x) in firstArray}
You can then iterate over your second array using list comprehension.
[[i[0], firstDict[i[1]]] for i in secondArray]
use a list comprehension:
In [119]: fa=[['AF','AFGHANISTAN'],['AL','ALBANIA'],['DZ','ALGERIA'],['AS','AMERICAN SAMOA']]
In [120]: sa=[[1,'AFGHANISTAN'],[3,'AMERICAN SAMOA']]
In [121]: [[y[0],x[0]] for x in fa for y in sa if y[1]==x[1]]
Out[121]: [[1, 'AF'], [3, 'AS']]
Related
I have a dictionary where the values are a list of tuples.
dictionary = {1:[('hello, how are you'),('how is the weather'),('okay
then')], 2:[('is this okay'),('maybe It is')]}
I want to make the values a single string for each key. So I made a function which does the job, but I do not know how to get insert it back to the original dictionary.
my function:
def list_of_tuples_to_string(dictionary):
for tup in dictionary.values():
k = [''.join(i) for i in tup] #joining list of tuples to make a list of strings
l = [''.join(k)] #joining list of strings to make a string
for j in l:
ki = j.lower() #converting string to lower case
return ki
output i want:
dictionary = {1:'hello, how are you how is the weather okay then', 2:'is this okay maybe it is'}
You can simply overwrite the values for each key in the dictionary:
for key, value in dictionary.items():
dictionary[key] = ' '.join(value)
Note the space in the join statement, which joins each string in the list with a space.
It can be done even simpler than you think, just using comprehension dicts
>>> dictionary = {1:[('hello, how are you'),('how is the weather'),('okay then')],
2:[('is this okay'),('maybe It is')]}
>>> dictionary = {key:' '.join(val).lower() for key, val in dictionary.items()}
>>> print(dictionary)
{1: 'hello, how are you how is the weather okay then', 2: 'is this okay maybe It is'}
Now, let's go through the method
we loop through the keys and values in the dictionary with dict.items()
assign the key as itself together with the value as a string consisting of each element in the list.
The elemts are joined together with a single space and set to lowercase.
Try:
for i in dictionary.keys():
dictionary[i]=' '.join(updt_key.lower() for updt_key in dictionary[i])
In python 3, I am trying to create an array of elements, where each element consists of two values. These values are not really key-value pairs because they are equally related to each other, meaning value 1 could be the key for value two, just as value two could be the key to value one and so I didn't think a dictionary was appropriate.
my_list = [ (VALUE1, OFFSET1), (VALUE2, OFFSET2) ]
def printList(list):
for item in list:
print(item)
How could I collect the VALUE and OFFSET "values" separately? Such as
theValue = list[0].VALUE
theOffset = list[0].OFFSET
I'm thinking an array of structs perhaps?
You can use zip, which transposes the list and collects elements at the same position to one element in the result:
value, offset = zip(*my_list)
value
#('VALUE1', 'VALUE2')
offset
#('OFFSET1', 'OFFSET2')
def printList(my_list):
for item in my_list:
print('Value ', item[0])
print('Offset ', item[1])
The for loop iterates through my_list. Each element in the loop is received as tuple like (VALUE, OFFSET) in the variable item. So item[0] is VALUE and item[1] is OFFSET. And we print it.
I'll do this like:
my_list = [ ("VALUE1", "OFFSET1"), ("VALUE2", "OFFSET2") ]
def printList(my_llst):
values = []
ofts = []
for item in my_llst:
values.append(item[0])
ofts.append(item[1])
return (values,ofts)
(['VALUE1', 'VALUE2'], ['OFFSET1', 'OFFSET2'])
Since you have a list of tuples, instead of:
theValue = list[0].VALUE
theOffset = list[0].OFFSET
You can use:
theValue = list[0][0]
theOffset = list[0][1]
So in your for-loop:
def printList(list):
for item in list:
print('VALUE: {}'.format(item[0]))
print('OFFSET: {}'.format(item[1]))
If you want to get all values in list and offsets in a separate list, you can use list-comprehension:
values = [x[0] for x in list]
offsets = [x[1] for x in list]
One more important thing, AVOID using built-in functions like list as variables, use something else instead.
Try using a list comprehension
theValue = [value[0] for value in my_list]
theOffset = [offset[0] for value in offset]
I think namedtuple can help you.
from collections import namedtuple
Element = namedtuple("Element", ["value", "offset"])
element_list = []
for value, offset in my_list:
element_list.append(Element(value, offset))
for element in element_list:
print element.value, element.offset
If you want to get all values and offsets separately, you can use numpy to transform my_list to numpy.array which is a 2d array.
import numpy as np
2d_array = np.array(my_list)
values = 2d_array[:, 0]
offsets = 2d_array[:, 1]
Suppose I have a dictionary with a tuple as key, such as the following:
d1 = {}
d1[(111,1)] = "value1111"
d1[(111,2)] = "value1112"
d1[(111,3)] = "value1113"
d1[(112,1)] = "value1121"
d1[(112,2)] = "value1122"
d1[(112,3)] = "value1123"
How can I get all the values for a given number in the first element of the tuple key? That is, for the 111, I want to obtain the following:
value1111
value1112
value1113
I've tried print(d1[(111,i)]) but it only returns one value, is there a simple way of doing this?
Thanks in advance.
Use list comprehension, this way:
[v for k,v in d1.items() if k[0]==111]
The condition if k[0]==111 means return only values of d1 whose key's first element is 111
You were also trying with print(d1[(111,i)],that will work if you have a control over the range and types of the second element of key's tuple, i.e:
>>> [d1[(111,i)] for i in range(1,4)]
['value1111', 'value1112', 'value1113']
In your example, we know that the i can only be from 1 to 3, hence range(1,4), but if you don't know what's the range of i and even what the type of i could be, then the list comprehension is your best friend here.
Of course, one can get the list of second element of key's tuple whose first element is 111 by doing so:
>>>my_filter = [k[1] for k in d1 if k[0]==111]
[2, 3, 1]
>>>my_list = [d1[(111,i) for i in my_filter]
['value1112', 'value1113', 'value1111']
A simple list comprehension will do the trick:
>>> [d1[tup] for tup in d1 if tup[0] == 111]
['value1112', 'value1113', 'value1111']
It says "for every key tup in the dictionary, give me the corresponding value if the key's first element is 111".
If you control how the dict is created and want to group by the first element of your tuples forget using tuples as keys and use a defaultdict appending to a list to handle repeated keys:
from collections import defaultdict
d1 = defaultdict(list)
d1[111].append("value1111")
d1[111].append( "value1112")
d1[111].append("value1113")
d1[112].append("value1121")
d1[112].append("value1122")
d1[112].apendd("value1123")
Then you can get all the values at once or index the list to pull the ith value:
In [17]: d1
Out[17]:
defaultdict(list,
{111: ['value1111', 'value1112', 'value1113'],
112: ['value1121', 'value1122']})
In [18]: d1[111]
Out[18]: ['value1111', 'value1112', 'value1113']
In [19]: d1[111][0]
Out[19]: 'value1111'
In [20]: d1[111][1]
Out[20]: 'value1112'
Honestly, I think the default dict approach is the most flexible and allows you to query other values easily (e.g. 112 or 113). In the code below, d2 will be a map from the 111, 112, 113 to their respective values.
d2 = defaultdict(list)
for key, value in d1.iteritems():
d2[key[0]].append(value)
print d2[111]
print d2[112]
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.
Let's say I have dict. I don't know the key/value inside. How do I get this key and the value without doing a for loop (there is only one item in the dict).
You might wonder why I am using a dictionary in that case. I have dictionaries all over my API and I don't want the user to be lost. It's only a matter of consistency. Otherwise, I would have used a list and indexes.
Use the proper data type for the job. Your goal should be to have workable code, not that you use the same data type all over the place.
If your dictionary only contains one key and one value, you can get either with indexing:
key = list(d)[0]
value = list(d.values())[0]
or to get both:
key, value = list(d.items())[0]
The list calls are needed because in Python 3, .keys(), .values() and .items() return dict views, not lists.
Another option is to use sequence unpacking:
key, = d
value, = d.values()
or for both at the same time:
(key, value), = d.items()
Just get the first item in the dictionary using an iterator
>>> d = {"foo":"bar"}
>>> k, v = next(iter(d.items()))
>>> k
'foo'
>>> v
'bar'
You can do this:
>>> d={1:'one'}
>>> k=list(d)[0]
>>> v=d[k]
Works in Python 2 or 3
d.popitem() will give you a key,value tuple.