Asked 7 years ago
26 Apr 2017
Views 1873
pratik

pratik posted

what is alternative in PYTHON for function array_flip of PHP ?

i know PHP very well , array_flip is my favorite function to exchange all value to associated key of array


$a=array("a","r","r","a","y");
array_flip($a);


it will change key to associated value
but does PYTHON have function like array_flip ?
or is there any alternative function like array_flip of PHP which replace key to associated value ?
why you need array_flip in PYTHON ? - Mitul Dabhi  
Apr 26 '17 01:50
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

first of all Python's Array do not have key and values .only have values.
use dictionary instead of Array

first approach to flip dictionary in PYTHON

dictionary = {"geeta":"good religion book" , "mahabharat":"epic peom","ramayan":"epic love story"}
results= dict(zip(dictionary.values(), dictionary.keys()))


dict.values function give all values.
dict.keys function give all keys.
zip function do very good job here . zip create an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables

but it return tuples convert it to dictionary by dict .

another approach to flip dictionary in PYTHON

results= [(v, k) for (k, v) in dictionary.items()]
print(results)


iterate with dictionary and get key and value and set it to another dictionary
Rasi

Rasi
answered Nov 30 '-1 00:00

simple way to flip associated key and values in dictionary


r= {"1":"first" , "2":"second","3":"third"}
for (k, v) in r.items():
    x[v]=k
print(x)


simply iterated the dictionary and set the values value to key .
Post Answer