Tsv to csv python

Python – How to convert a .tsv to .csv

How can I merge two Python dictionaries in a single expression?

For dictionaries x and y , z becomes a shallowly-merged dictionary with values from y replacing those from x .

    In Python 3.9.0 or greater (released 17 October 2020): PEP-584, discussed here, was implemented and provides the simplest method:

def merge_two_dicts(x, y): z = x.copy() # start with keys and values of x z.update(y) # modifies z with keys and values of y return z 

Explanation

Say you have two dictionaries and you want to merge them into a new dictionary without altering the original dictionaries:

The desired result is to get a new dictionary ( z ) with the values merged, and the second dictionary’s values overwriting those from the first.

A new syntax for this, proposed in PEP 448 and available as of Python 3.5, is

And it is indeed a single expression.

Note that we can merge in with literal notation as well:

It is now showing as implemented in the release schedule for 3.5, PEP 478, and it has now made its way into the What’s New in Python 3.5 document.

However, since many organizations are still on Python 2, you may wish to do this in a backward-compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:

z = x.copy() z.update(y) # which returns None since it mutates z 

In both approaches, y will come second and its values will replace x ‘s values, thus b will point to 3 in our final result.

Not yet on Python 3.5, but want a single expression

If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a single expression, the most performant while the correct approach is to put it in a function:

def merge_two_dicts(x, y): """Given two dictionaries, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z 

and then you have a single expression:

You can also make a function to merge an arbitrary number of dictionaries, from zero to a very large number:

def merge_dicts(*dict_args): """ Given any number of dictionaries, shallow copy and merge into a new dict, precedence goes to key-value pairs in latter dictionaries. """ result = <> for dictionary in dict_args: result.update(dictionary) return result 

This function will work in Python 2 and 3 for all dictionaries. e.g. given dictionaries a to g :

z = merge_dicts(a, b, c, d, e, f, g) 

and key-value pairs in g will take precedence over dictionaries a to f , and so on.

Critiques of Other Answers

Don’t use what you see in the formerly accepted answer:

In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. In Python 3, this will fail because you’re adding two dict_items objects together, not two lists —

>>> c = dict(a.items() + b.items()) Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items' 

and you would have to explicitly create them as lists, e.g. z = dict(list(x.items()) + list(y.items())) . This is a waste of resources and computation power.

Читайте также:  У target result javascript

Similarly, taking the union of items() in Python 3 ( viewitems() in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, since sets are semantically unordered, the behavior is undefined in regards to precedence. So don’t do this:

This example demonstrates what happens when values are unhashable:

>>> x = >>> y = >>> dict(x.items() | y.items()) Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list' 

Here’s an example where y should have precedence, but instead the value from x is retained due to the arbitrary order of sets:

>>> x = >>> y = >>> dict(x.items() | y.items())

Another hack you should not use:

This uses the dict constructor and is very fast and memory-efficient (even slightly more so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it’s difficult to read, it’s not the intended usage, and so it is not Pythonic.

Here’s an example of the usage being remediated in django.

Dictionaries are intended to take hashable keys (e.g. frozenset s or tuples), but this method fails in Python 3 when keys are not strings.

>>> c = dict(a, **b) Traceback (most recent call last): File "", line 1, in TypeError: keyword arguments must be strings 

From the mailing list, Guido van Rossum, the creator of the language, wrote:

I am fine with declaring dict(<>, **) illegal, since after all it is abuse of the ** mechanism.

Apparently dict(x, **y) is going around as «cool hack» for «call x.update(y) and return x». Personally, I find it more despicable than cool.

It is my understanding (as well as the understanding of the creator of the language) that the intended usage for dict(**y) is for creating dictionaries for readability purposes, e.g.:

Response to comments

Despite what Guido says, dict(x, **y) is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-coming of dict. Nor is using the ** operator in this place an abuse of the mechanism, in fact, ** was designed precisely to pass dictionaries as keywords.

Again, it doesn’t work for 3 when keys are not strings. The implicit calling contract is that namespaces take ordinary dictionaries, while users must only pass keyword arguments that are strings. All other callables enforced it. dict broke this consistency in Python 2:

>>> foo(**<('a', 'b'): None>) Traceback (most recent call last): File "", line 1, in TypeError: foo() keywords must be strings >>> dict(**<('a', 'b'): None>)

This inconsistency was bad given other implementations of Python (PyPy, Jython, IronPython). Thus it was fixed in Python 3, as this usage could be a breaking change.

I submit to you that it is malicious incompetence to intentionally write code that only works in one version of a language or that only works given certain arbitrary constraints.

dict(x.items() + y.items()) is still the most readable solution for Python 2. Readability counts.

My response: merge_two_dicts(x, y) actually seems much clearer to me, if we’re actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated.

<**x, **y>does not seem to handle nested dictionaries. the contents of nested keys are simply overwritten, not merged [. ] I ended up being burnt by these answers that do not merge recursively and I was surprised no one mentioned it. In my interpretation of the word «merging» these answers describe «updating one dict with another», and not merging.

Yes. I must refer you back to the question, which is asking for a shallow merge of two dictionaries, with the first’s values being overwritten by the second’s — in a single expression.

Assuming two dictionaries of dictionaries, one might recursively merge them in a single function, but you should be careful not to modify the dictionaries from either source, and the surest way to avoid that is to make a copy when assigning values. As keys must be hashable and are usually therefore immutable, it is pointless to copy them:

from copy import deepcopy def dict_of_dicts_merge(x, y): z = <> overlapping_keys = x.keys() & y.keys() for key in overlapping_keys: zTsv to csv python = dict_of_dicts_merge(xTsv to csv python, yTsv to csv python) for key in x.keys() - overlapping_keys: zTsv to csv python = deepcopy(xTsv to csv python) for key in y.keys() - overlapping_keys: zTsv to csv python = deepcopy(yTsv to csv python) return z 
>>> x = >, 'b': >> >>> y = >, 'c': >> >>> dict_of_dicts_merge(x, y) , 10: <>>, 'a': >, 'c': >> 

Coming up with contingencies for other value types is far beyond the scope of this question, so I will point you at my answer to the canonical question on a «Dictionaries of dictionaries merge».

Less Performant But Correct Ad-hocs

These approaches are less performant, but they will provide correct behavior. They will be much less performant than copy and update or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they do respect the order of precedence (latter dictionaries have precedence)

You can also chain the dictionaries manually inside a dict comprehension:

or in Python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):

dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2 

itertools.chain will chain the iterators over the key-value pairs in the correct order:

from itertools import chain z = dict(chain(x.items(), y.items())) # iteritems in Python 2 

Performance Analysis

I’m only going to do the performance analysis of the usages known to behave correctly. (Self-contained so you can copy and paste yourself.)

from timeit import repeat from itertools import chain x = dict.fromkeys('abcdefg') y = dict.fromkeys('efghijk') def merge_two_dicts(x, y): z = x.copy() z.update(y) return z min(repeat(lambda: <**x, **y>)) min(repeat(lambda: merge_two_dicts(x, y))) min(repeat(lambda: )) min(repeat(lambda: dict(chain(x.items(), y.items())))) min(repeat(lambda: dict(item for d in (x, y) for item in d.items()))) 
>>> min(repeat(lambda: <**x, **y>)) 1.0804965235292912 >>> min(repeat(lambda: merge_two_dicts(x, y))) 1.636518670246005 >>> min(repeat(lambda: )) 3.1779992282390594 >>> min(repeat(lambda: dict(chain(x.items(), y.items())))) 2.740647904574871 >>> min(repeat(lambda: dict(item for d in (x, y) for item in d.items()))) 4.266070580109954 
$ uname -a Linux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux 

Resources on Dictionaries

  • My explanation of Python’s dictionary implementation, updated for 3.6.
  • Answer on how to add new keys to a dictionary
  • Mapping two lists into a dictionary
  • The official Python docs on dictionaries
  • The Dictionary Even Mightier — talk by Brandon Rhodes at Pycon 2017
  • Modern Python Dictionaries, A Confluence of Great Ideas — talk by Raymond Hettinger at Pycon 2017
Python – How to check if a list is empty
if not a: print("List is empty") 

Using the implicit booleanness of the empty list is quite pythonic.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Haavi97/Simple-TSV-to-CSV-converter

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Simple TSV to CSV converter

CLI app to convert TSV files to CSV files

Simplest usage is to run directly with the file name from the CLI:

python tsv_to_csv.py file_name

Usage adding encoding and separator

If you want to add the encoding you can add an additional encoding (by default is utf-8) and separator (by default is ,) parameters:

python tsv_to_csv.py file_name encoding separator

If you want a guided step by step just set the guided parameter:

python tsv_to_csv.py --guided

and you will be prompted something like:

foo@bar:~$ python tsv_to_csv.py --guided Please, provide the file name: filename.tsv Please, provide file encoding: utf-8 Succesfully converted foo@bar:~$

Источник

Оцените статью