How to build dictionary from two lists [duplicate] - python

This question already has answers here:
How can I make a dictionary (dict) from separate lists of keys and values?
(21 answers)
Closed 8 years ago.
With two lists of different sizes:
numbers=[1,2,3,4,5]
cities=['LA','NY','SF']
I need to get this:
result={1:'LA', 2:'NY', 3:'SF'}
I thought of doing it with:
result={number:cities[numbers.index(number)] for number in numbers if numbers.index(number)<len(cities)}
But this one-liner gets kind of long. I wonder if there is an alternative way of achieving the same goal.
EDITED LATER:
There were multiple suggestions made to use zip:
dict(zip(cities, numbers))
While it is a definitely a simpler syntax than list comprehension I've used I wonder which would be faster to execute?

Use zip, it will only zip upto the end of the shortest sequence
dict(zip(cities, numbers))

numbers=[1,2,3,4,5]
cities=['LA','NY','SF']
dict(zip(cities,numbers))
;)
I suspect it is duplicate though - search before you post

The easiest is probably dict(zip(numbers,cities))
zip will stop once any of the lists ends, which is what you want.

Related

List converted to string [duplicate]

This question already has answers here:
How would you make a comma-separated string from a list of strings?
(15 answers)
Closed 6 years ago.
I'm new to python, and have a list of longs which I want to join together into a comma separated string.
In PHP I'd do something like this:
$output = implode(",", $array)
In Python, I'm not sure how to do this. I've tried using join, but this doesn't work since the elements are the wrong type (i.e., not strings). Do I need to create a copy of the list and convert each element in the copy from a long into a string? Or is there a simpler way to do it?
You have to convert the ints to strings and then you can join them:
','.join([str(i) for i in list_of_ints])
You can use map to transform a list, then join them up.
",".join( map( str, list_of_things ) )
BTW, this works for any objects (not just longs).
You can omit the square brackets from heikogerlach's answer since Python 2.5, I think:
','.join(str(i) for i in list_of_ints)
This is extremely similar, but instead of building a (potentially large) temporary list of all the strings, it will generate them one at a time, as needed by the join function.
and yet another version more (pretty cool, eh?)
str(list_of_numbers)[1:-1]
Just for the sake of it, you can also use string formatting:
",".join("{0}".format(i) for i in list_of_things)

Zip in Python: How to return tuples instead of a zip object [duplicate]

This question already has answers here:
Python range() and zip() object type
(3 answers)
Closed 2 years ago.
I am currently using Python 3.7.3 and am relatively new. My understanding was that the zip() function returns a list of tuples, however in practice I have found it returns a 'zip' object. Is there a way that I can get this function to return a list of tuples or a similar function that can accomplish my purpose?
Thanks so much!
I don't know if that was automatic or a mod did that, but thank you!
All you need to do is convert it to a list.
list(zip(....))

Itertools Combinations/Permutations size [duplicate]

This question already has answers here:
Is there any built-in way to get the length of an iterable in python?
(10 answers)
What's the shortest way to count the number of items in a generator/iterator?
(7 answers)
Closed 4 years ago.
Is there anyway to see the len() of an itertools.Combination or other object, really, without materializing it to a list?
I can get the cardinality of combs or permutations with the factorials,... but I want something that generalizes.
Thanks
For any iterable it, you can do:
length = sum(1 for ignore in it)
That doesn't create a list, so the memory footprint is small. But for many kinds of iterables, it also consumes it (for example, if it is a generator, it's consumed and can't be restarted; if it is a list, it's not consumed). There is no generally "non-destructive" way to determine the length of an arbitrary iterable.
Also note that the code above will run "forever" if it delivers an unbounded sequence of objects.
No need to create a list. You can count the number of items in an iterable without storing the entire set:
sum(1 for _ in myIterable)
Yes,
def count_iterable(i):
return sum(1 for e in i)
Taken from: Is there any built-in way to get the length of an iterable in python?

Confused about the output from set() in Python(2.4.3) [duplicate]

This question already has answers here:
Why is the order in dictionaries and sets arbitrary?
(5 answers)
Closed 6 years ago.
I am a beginner in python and I am using python 2.4.3.
I have a question regarding to the order resulted from the set()function.
I understand set() will remove the the duplicate elements from a string and
[class set([iterable])
Return a new set object, optionally with elements taken from iterable.]1
But for example, when I do the following
a='abcdabcd'
set(a)
it returned a result of
set(['a','c','b','d'])
in stead of
set(['a','b','c','d'])
which I would actually expect.
Why is that? I am not able to understand how the output was generated.
Many thanks in advance.
A set is defined as an "unordered collection of unique elements" (see here). The set object in Python make no guarantees about ordering, and you should not expect nor rely on the order to stay the same.

How to use the list index in a for loop? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Finding the index of a list in a loop
Assume you have a list, where not just the values have meaning, the index has, too.
counts = [3,4,5,3,1]
Let's say that means "we have 3 objects of type zero, 4 objects of type 1 and so on".
You want to create a list of objects from that and give these objects both information details:
[CountObject(amount=a,type=???) for a in counts]
How would you do that?
Use the enumerate() function:
[CountObject(amount=a, type=i) for i, a in enumerate(counts)]
where i is then the index.
Something like:
[CountObject(amount=counts[a],type=a) for a in range(len(counts))]
would do what you want i guess .
beside enumerate() you can also try range(), use xrange() if you're on python 2.x:
[CountObject(amount=counts[i],type=i) for i in range(len(counts))]

Categories